JS字符串属性和方法集锦

10,307 阅读2分钟

JavaScript字符串属性方法

方法1.length

length决定字符串的长度

例:


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

方法2.slice

slice() 提取字符串的某个部分并在新字符串中返回被提取的部分。

该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。

这个例子裁剪字符串中位置 5 到位置 14 的片段:


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

方法3.substring

(开始的索引,结束的索引);返回截取后的字符串,不包含结束的索引的字符串

substring() 类似于 slice()。 不同之处在于 substring() 无法接受负的索引。

这个例子裁剪字符串中位置 6 到位置 13 的片段:


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

方法4.split

切割字符串


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

方法5.indexOf

indexOf() 方法返回字符串中指定文本首次出现的索引(位置):

indexOf(要找的字符串,从某个位置开始的索引);返回的是这个字符串的索引值,没有则-1


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

方法6.lastIndexOf

lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引:

lastIndexOf(要找的字符串);从后往前找,但是索引仍然是从左往右的方式,找不到则返回-1


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

方法7.charAt

charAt() 方法返回字符串中指定下标(位置)的字符串:

当超出索引时,结果是空字符串


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

以上就是JS字符串的部分方法。