JavaScript string property method

Methods 1. Length

Length determines the length of the string

Ex. :


var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string = txt.length;
// string = 26;

Copy the code

Methods 2. Slice

Slice () extracts a portion of the string and returns the extracted portion in a new string.

This method sets two parameters: the start index (start position) and the end index (end position).

This example clips the fragment from position 5 to position 14 in the string:


var str = "How old are you?";
var res = str.slice(5.14);
// res = ld are yo;

Copy the code

Methods 3. The substring

(start index, end index); Returns a truncated string that does not contain the terminated index

Substring () is similar to slice(). The difference is that substring() cannot accept negative indexes.

This example clipped the string fragment from position 6 to position 13:


var str = "How old are you?";
var res = str.slice(6.13);
// res = d are y;

Copy the code

Method 4. The split

Cut string


var str = "How old are you?";
var res = str.split('o');
// res = H,w ,ld are y,u? ;

Copy the code

Methods 5. IndexOf

The indexOf() method returns the index (position) of the first occurrence of the specified text in the string:

IndexOf (the string to find, the index from a certain position); Returns the index of the string, minus 1


var str = "The full name of the United States is the United States of America.";
var pos = str.indexOf("United");
// pos = 21;

Copy the code

Methods 6. LastIndexOf

The lastIndexOf() method returns the index of the last occurrence of the specified text in the string:

LastIndexOf (string to find); Search from back to front, but the index is still left to right, if it cannot find -1


var str = "The full name of the United States is the United States of America.";
var pos = str.lastIndexOf("United");
// pos = 42;

Copy the code

Methods 7. CharAt

The charAt() method returns a string with the specified subscript (position) in the string:

When the index is exceeded, the result is an empty string


var str = "The full name of the United States is the United States of America.";
var pos = str.charAt("10");
// pos = a;

Copy the code

That’s part of the JS string method.