Strings

Strings are primitive types in JavaScript that can be created with single quotes or double quotes. There is no difference. It's only a matter of style. ES2015 introduced two new string features: template literals and multiline strings.

Multiline strings can be created by adding a backslash at the end of each line:

const line = "Multiline strings can be 
reated adding a backslash
at the end of each line";

Template literals are strings created with backticks. They allow the inclusion of JavaScript expressions inside the ${} placeholders. The result is concatenated as a single string:

const template = `The square root of 2 is ${Math.sqrt(2)}`;

If you need to use a special character in a string, such as a double quote in a double-quoted string or a backslash, you need to precede it with a backslash:

const s = "This is a backslash \ and this is a double quote "";

There are several methods for string manipulation. They all return new strings or other types. No methods modify the original strings:

Method

Description

Example

startsWith(s)

Returns true if the string starts with the string passed as a parameter.

const s = "This is a test string"
const r = s.startsWith("This");
// true

endsWith(s)

Returns true if string ends with the string passed as a parameter.

const s = "This is a test string"
const r = s.endsWith("This");
// false

substring(s,e)

Returns a substring between start (incl.) and end indexes (not incl.).

const k = "Aardvark"
const ardva = k.substring(1,6);

split(regx)

split(delim)

Splits a string by a delimiter character or  a regular expression and returns an array.

const result = s.split(" ");
// result =
//["This","is","a","test","string"]

indexOf()

Returns the index of the first occurrence of a substring.

const k = "Aardvark"
const i = k.indexOf("ar"); // i = 1

lastIndexOf()

Returns the index of the last occurrence of a substring.

const k = "Aardvark"
const i = k.lastIndexOf("ar");
// i = 5

charAt(i)

Returns char at index i. Also supported as ‘string'[i].

const k = "Aardvark"
const v = k.charAt(4);

trim()

Removes whitespace from both ends of a string.

const text = "   data   "
const r = data.trim();
// r = "data"

match(regx)

Returns an array as the result of matching a regular expression against the string.

const k = "Aardvark"
const v = k.match(/[a-f]/g);
// v = ["a", "d", "a"]

replace(regx,r)

replace(s,t)

Returns a new string replacing the matching of regexp applied to the string with a replacement or all occurrences of the source string with a target string.

const k = "Aardvark"
const a = p.replace(/a/gi, 'u')
// a = "uurdvurk"
const b = p.replace('ardv', 'ntib')
// b = "Antibark"
JavaScript functions for string manipulation
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset