This is the 9th day of my participation in the More text Challenge. For details, see more text Challenge

JavaScript string attribute methods

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 part of the string and returns the extracted part in the new string.

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

This example clips a string from position 5 to position 14:


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 the truncated string without the ending index

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

This example clips a string 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

Split 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, without -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 (the string to look for); Look back, but the index is still left to right. If you can’t find it, return -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 a specified subscript (position) in the string:

When out of index, 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

Those are some of the methods for JS strings.