JavaScript String

Strings in JavaScript are basic values. Strings are also permanent. It means that you will always obtain a new string if you edit one. The initial string remains unchanged. 

To create literal strings, you use either single quotes (') or double quotes (") like this:

let str = 'Hi';
let greeting = "Hello";
Code language: JavaScript (javascript)

ES6 introduced template literals that allow you to define a string backtick (`) characters:

let name = `Rocky`';
Code language: JavaScript (javascript)

The template literals allow you to use the single quotes and double quotes inside a string without the need of escaping them. For example:

let mesage = `"I'm good". She said";
Code language: JavaScript (javascript)

Also, you can place the variables and expressions inside a template literal. JavaScript will replace the variables with their value in the string. This is called string interpolation. For example:

let name = 'Rocky';
let message = `Hi, I'm ${name}.`;

console.log(message);

Code language: JavaScript (javascript)

Output:

Hi, I'm Rocky.

In this example, JavaScript replaces the name variable with its value inside the template literal.

Escaping special characters

To escape special characters, you use the backslash \ character. For example:

  • Windows line break: '\r\n'
  • Unix line break: '\n'
  • Tab: '\t'
  • Backslash '\'

The following example uses the backslash character to escape the single quote character in a string:

let str = 'I\'m a string!';
Code language: JavaScript (javascript)

Getting the length of the string

The length property returns the length of a string:

let str = "Good Morning!";
console.log(str.length); // 13
Code language: JavaScript (javascript)

Note that JavaScript has the String type (with the letter S in uppercase), which is the primitive wrapper type of the primitive string type. Therefore, you can access all properties and methods of the String type from a primitive string.

Accessing characters

Use the array-like [] syntax and the zero-based index to retrieve the characters in a string. The first character of a string with index zero is returned in the example below:

let str = "Hello";
console.log(str[0]); // "H"
Code language: JavaScript (javascript)

To access the last character of the string, you use the length - 1 index:

let str = "Hello";
console.log(str[str.length -1]); // "o"
Code language: JavaScript (javascript)

Concatenating strings via + operator

To concatenate two or more strings, you use the + operator:

let name = 'John';
let str = 'Hello ' + name;

console.log(str); // "Hello Rocky"

Code language: JavaScript (javascript)

If you want to assemble a string piece by piece, you can use the += operator:

let className = 'btn';
className += ' btn-primary'
className += ' none';

console.log(className);

Code language: JavaScript (javascript)

Output:

btn btn-primary none
Code language: JavaScript (javascript)

Converting values to string

To convert a non-string value to a string, you use one of the following:

  • String(n);
  • ” + n
  • n.toString()

Note that the toString() the method doesn’t work for undefined and null.

When you convert a string to a boolean, you cannot convert it back. For example:

let status = false;
let str = status.toString(); // "false"
let back = Boolean(str); // true
Code language: JavaScript (javascript)

In this example:

  • First, declare the status variable and initialize it with the value of false.
  • Second, convert the status variable to a string using the toString() method.
  • Third, convert the string back to a boolean value using the Boolean() function. The Boolean() function converts the string "false" to a boolean value. The result is true because "false" is a non-empty string.

Note that only string for which the Boolean() returns false, is the empty string ('');

Comparing strings

To compare two strings, you use comparison operators such as >>=<<=, and == operators.

The numeric values of the characters are used by comparison operators to compare strings. Additionally, it might produce a string order that differs from the one seen in dictionaries. For instance:

let result = 'a' < 'b';
console.log(result); // true
Code language: JavaScript (javascript)

However:

let result = 'a' < 'B';
console.log(result); // false
Code language: JavaScript (javascript)

JavaScript Multiline Strings

To use a multiline string, you can either use the + operator or the \ operator. For example,

// using the + operator
const message1 = 'This is a long message ' +
    'that spans across multiple lines' + 
    'in the code.'

// using the \ operator
const message2 = 'This is a long message \
that spans across multiple lines \
in the code.'

JavaScript String Length

To find the length of a string, you can use built-in length property. For example,

const a = 'hello';
console.log(a.length); // 5

JavaScript String Objects

You can also create strings using the new keyword. For example,

const a = 'hello';
const b = new String('hello');

console.log(a); // "hello"
console.log(b); // "hello"

console.log(typeof a); // "string"
console.log(typeof b); // "object"

.

Note: It is recommended to avoid using string objects. Using string objects slows down the program.

JavaScript String Methods

Here are the commonly used JavaScript String methods:

Method Description
charAt(index) returns the character at the specified index
concat() joins two or more strings
replace() replaces a string with another string
split() converts the string to an array of strings
substr(start, length) returns a part of a string
substring(start,end) returns a part of a string
slice(start, end) returns a part of a string
toLowerCase() returns the passed string in lower case
toUpperCase() returns the passed string in the upper case
trim() removes whitespace from the strings
includes() searches for a string and returns a boolean value
search() searches for a string and returns a position of a match

Example: JavaScript String Methods

const text1 = 'hello';
const text2 = 'world';
const text3 = '     JavaScript    ';

// concatenating two strings
const result1 = text1.concat(' ', text2);
console.log(result1); // "hello world"

// converting the text to uppercase
const result2 = text1.toUpperCase();
console.log(result2); // HELLO

// removing whitespace from the string
const result3 = text3.trim();
console.log(result3); // JavaScript

// converting the string to an array
const result4 = text1.split();
console.log(result4); // ["hello"]

// slicing the string
const result5= text1.slice(1, 3);
console.log(result5); // "el"

JavaScript String() Function


The String() the function is used to convert various data types to strings. For example,

const a = 225; // number
const b = true; // boolean

//converting to string
const result1 = String(a);
const result2 = String(b);

console.log(result1); // "225"
console.log(result2); // "true"

Escape Character

You can use the backslash escape character \ to include special characters in a string. For example 

const name = 'My name is \'Bikash\'.';
console.log(name);

Output

My name is 'Bikash'.

In the above program, the same quote is included using \.

Here are other ways that you can use \:

Code Output
\” include double quote
\\ include backslash
\n new line
\r carriage return
\v vertical tab
\t horizontal tab
\b backspace
\f form feed

Summary

  • Strings in JavaScript are non – modifiable primitive values.
  • Literal strings are delimited by single quotes ('), double quotes ("), or backticks (`).
  • The length property returns the length of the string.
  • Use the comparison operators `>, >=, <, <=, == to compare strings.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *