- JavaScript string
- Introduction to the JavaScript strings
- Escaping special characters
- Getting the length of the string
- Accessing characters
- Concatenating strings via + operator
- Converting values to string
- Comparing strings
- Summary
- JavaScript String Reference
- String Properties and Methods
- JavaScript String Methods
- Note
- String HTML Wrapper Methods
JavaScript string
Summary: in this tutorial, you’ll learn about the JavaScript string primitive type and how to use it to define strings.
Introduction to the JavaScript strings
JavaScript strings are primitive values. Also, strings are immutable. It means that if you modify a string, you will always get a new string. The original string doesn’t change.
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 = `John`';
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 = 'John'; let message = `Hi, I'm $ .`; console.log(message);
Code language: JavaScript (javascript)
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:
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
To access the characters in a string, you use the array-like [] notation with the zero-based index. The following example returns the first character of a string with the index zero:
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
let name = 'John'; let str = 'Hello ' + name; console.log(str); // "Hello John"
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)
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:
Note that the toString() 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)
- First, declare the status variable and initialize its 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
The comparison operators compare strings based on the numeric values of the characters. And it may return the string order that is different from the one used in dictionaries. For example:
let result = 'a' < 'b'; console.log(result); // true
Code language: JavaScript (javascript)
let result = 'a' < 'B'; console.log(result); // false
Code language: JavaScript (javascript)
Summary
- JavaScript strings are primitive values and immutable.
- Literal strings are delimited by single quotes ( ‘ ), double quotes ( » ), or backticks (`).
- The length property returns the length of the string.
- Use the comparison operators `>, >=,
JavaScript String Reference
A JavaScript string stores a series of characters like «John Doe».
A string can be any text inside double or single quotes:
String indexes are zero-based:
The first character is in position 0, the second in 1, and so on.
For a tutorial about Strings, read our JavaScript String Tutorial.
String Properties and Methods
Normally, strings like «John Doe», cannot have methods or properties because they are not objects.
But with JavaScript, methods and properties are also available to strings, because JavaScript treats strings as objects when executing methods and properties.
JavaScript String Methods
Name | Description |
---|---|
charAt() | Returns the character at a specified index (position) |
charCodeAt() | Returns the Unicode of the character at a specified index |
concat() | Returns two or more joined strings |
constructor | Returns the string’s constructor function |
endsWith() | Returns if a string ends with a specified value |
fromCharCode() | Returns Unicode values as characters |
includes() | Returns if a string contains a specified value |
indexOf() | Returns the index (position) of the first occurrence of a value in a string |
lastIndexOf() | Returns the index (position) of the last occurrence of a value in a string |
length | Returns the length of a string |
localeCompare() | Compares two strings in the current locale |
match() | Searches a string for a value, or a regular expression, and returns the matches |
prototype | Allows you to add properties and methods to an object |
repeat() | Returns a new string with a number of copies of a string |
replace() | Searches a string for a pattern, and returns a string where the first match is replaced |
replaceAll() | Searches a string for a pattern and returns a new string where all matches are replaced |
search() | Searches a string for a value, or regular expression, and returns the index (position) of the match |
slice() | Extracts a part of a string and returns a new string |
split() | Splits a string into an array of substrings |
startsWith() | Checks whether a string begins with specified characters |
substr() | Extracts a number of characters from a string, from a start index (position) |
substring() | Extracts characters from a string, between two specified indices (positions) |
toLocaleLowerCase() | Returns a string converted to lowercase letters, using the host’s locale |
toLocaleUpperCase() | Returns a string converted to uppercase letters, using the host’s locale |
toLowerCase() | Returns a string converted to lowercase letters |
toString() | Returns a string or a string object as a string |
toUpperCase() | Returns a string converted to uppercase letters |
trim() | Returns a string with removed whitespaces |
trimEnd() | Returns a string with removed whitespaces from the end |
trimStart() | Returns a string with removed whitespaces from the start |
valueOf() | Returns the primitive value of a string or a string object |
Note
All string methods return a new value.
They do not change the original variable.
String HTML Wrapper Methods
HTML wrapper methods return a string wrapped inside an HTML tag.
These are not standard methods, and may not work as expected.
Method | Description |
---|---|
anchor() | Displays a string as an anchor |
big() | Displays a string using a big font |
blink() | Displays a blinking string |
bold() | Displays a string in bold |
fixed() | Displays a string using a fixed-pitch font |
fontcolor() | Displays a string using a specified color |
fontsize() | Displays a string using a specified size |
italics() | Displays a string in italic |
link() | Displays a string as a hyperlink |
small() | Displays a string using a small font |
strike() | Displays a string with a strikethrough |
sub() | Displays a string as subscript text |
sup() | Displays a string as superscript text |