Extension methods

Substring identification

Before ES6, the indexOf method was used to determine whether a string contains a substring. ES6 added new methods for substring identification.

  • includes(): Returns a boolean value, indicating whether the parameter string was found.
  • startsWith(): Returns a boolean value, indicating whether the parameter string is at the beginning of the original string.
  • endsWith(): Returns a boolean value, indicating whether the parameter string is at the end of the original string.

All three methods above accept two parameters: the string to search for, and an optional search start position index.

let string = "apple,banana,orange"; string.includes("banana"); // true string.startsWith("apple"); // true string.endsWith("apple"); // false string.startsWith("banana",6) // true

Notes:

  • These three methods only return boolean values. If you need to know the position of the substring, you still need to use indexOf and lastIndexOf.
  • If a regular expression is passed to these three methods instead of a string, an error is thrown. However, indexOf and lastIndexOf convert the regular expression into a string and search for it.

String repetition

repeat(): Returns a new string, indicating that the string is repeated the specified number of times.

console.log("Hello,".repeat(2));  // "Hello,Hello,"

If the parameter is a decimal, round down.

console.log("Hello,".repeat(3.2));  // "Hello,Hello,Hello,"

If the parameter is a decimal between 0 and -1, rounding is performed. A decimal between 0 and -1 rounds to -0, which is equivalent to repeating zero times.

console.log("Hello,".repeat(-0.5));  // "" 

If the parameter is NaN, it is equivalent to repeating zero times.

console.log("Hello,".repeat(NaN));  // "" 

If the parameter is negative or Infinity, an error is thrown:

console.log("Hello,".repeat(-1));  
// RangeError: Invalid count value

console.log("Hello,".repeat(Infinity));  
// RangeError: Invalid count value

If the parameter passed is a string, the string will first be converted into a number.

console.log("Hello,".repeat("hh")); // ""
console.log("Hello,".repeat("2"));  // "Hello,Hello,"

String padding

  • padStart: Returns a new string, indicating that the original string is padded from the head (left side) with the parameter string.
  • padEnd: Returns a new string, indicating that the original string is padded from the tail (right side) with the parameter string.

The above two methods accept two parameters: the first parameter specifies the minimum length of the generated string, and the second parameter is the string used for padding. If the second parameter is not specified, spaces are used by default.

console.log("h".padStart(5,"o"));  // "ooooh"
console.log("h".padEnd(5,"o"));    // "hoooo"
console.log("h".padStart(5));      // "    h"

If the specified length is less than or equal to the length of the original string, the original string is returned:

console.log("hello".padStart(5,"A"));  // "hello"

If the length of the original string plus the padding string is greater than the specified length, the excess padding string is truncated:

console.log("hello".padEnd(10,",world!"));  // "hello,worl"

Often used for padding digit positions:

console.log("123".padStart(10,"0"));  // "0000000123"

Template strings

Template strings are equivalent to an enhanced version of strings, using backticks`, in addition to being used as ordinary strings, they can also be used to define multi-line strings, and variables and expressions can be added into the string.

Basic usage

Ordinary strings

let string = `Hello'\n'world`; console.log(string); // "Hello' // 'world"

Multi-line strings:

let string1 = `Hey, can you stop angry now?`; console.log(string1); // Hey, // can you stop angry now?

Inserting variables and expressions into strings.

Variable names are written in ${}, and JavaScript expressions can be placed inside ${}.

let name = "Mike"; let age = 27; let info = `My Name is ${name},I am ${age+1} years old next year.` console.log(info); // My Name is Mike,I am 28 years old next year.

Calling functions in a string:

function f(){ return "have fun!"; } let string2= `Game start,${f()}`; console.log(string2); // Game start,have fun!

Key points to note

Line breaks and spaces in template strings are preserved.

innerHtml = `<ul> <li>menu</li> <li>mine</li> </ul> `; console.log(innerHtml); //Output <ul> <li>menu</li> <li>mine</li> </ul>

Tagged templates

A tagged template is a function call, where the parameter passed in is a template string.

alert`Hello world!`; //Equivalent to alert('Hello world!');

When a template string contains variables, the template string parameter is processed into multiple parameters.

function f(stringArr,...values){ let result = ""; for(let i=0;i<stringArr.length;i++){ result += stringArr[i]; if(values[i]){ result += values[i]; } } return result; } let name = 'Mike'; let age = 27; f`My Name is ${name},I am ${age+1} years old next year.`; // "My Name is Mike,I am 28 years old next year." f`My Name is ${name},I am ${age+1} years old next year.`; //Equivalent to f(['My Name is',',I am ',' years old next year.'],'Mike',28);

Applications

Filter HTML strings to prevent users from entering malicious content.

function f(stringArr,...values){ let result = ""; for(let i=0;i<stringArr.length;i++){ result += stringArr[i]; if(values[i]){ result += String(values[i]).replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;"); } } return result; } name = '<Amy&MIke>'; f`<p>Hi, ${name}.I would like send you some message.</p>`; // <p>Hi, &lt;Amy&amp;MIke&gt;.I would like send you some message.</p>

Internationalization processing (converting into multiple languages)

i18n`Hello ${name}, you are visitor number ${visitorNumber}.`; //Hello**, you are visitor number **