split()
可以通过 split() 将字符串转换为数组
var txt = "a,b,c,d,e"; // 字符串
txt.split(","); // ["a", "b", "c", "d", "e"]
txt.split(" "); // ["a,b,c,d,e"]
txt.split("|"); // ["a,b,c,d,e"]
txt.split(""); // ["a", ",", "b", ",", "c", ",", "d", ",", "e"]
charCodeAt()
方法返回字符串中指定索引的字符 unicode 编码
var str = "HELLO WORLD";
str.charCodeAt(0); // 返回 72
charAt()
方法返回字符串中指定下标(位置)的字符串
var str = "HELLO WORLD";
str.charAt(0); // H
trim()
方法删除字符串两端的空白符:
var str = " Hello World! ";
alert(str.trim()); // Hello World!
// str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
concat()
concat() 连接两个或多个字符串,字符串是不可变的:字符串不能更改,只能替换
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");
toLowerCase()
通过 toLowerCase() 把字符串转换为小写
var text1 = "Hello World!"; // 字符串
var text2 = text1.toLowerCase(); // "hello world!"
toUpperCase()
通过 toUpperCase() 把字符串转换为大写
var text1 = "Hello World!"; // 字符串
var text2 = text1.toUpperCase(); // "HELLO WORLD!"
replace()
方法用另一个值替换在字符串中指定的值,replace() 方法不会改变调用它的字符串。它返回的是新字符串。 默认地,replace() 只替换首个匹配。
- replace() 对大小写敏感
- 如需执行大小写不敏感的替换,请使用正则表达式 /i(大小写不敏感)
- 正则表达式不带引号。如需替换所有匹配,请使用正则表达式的 g 标志(用于全局搜索)
str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3School"); //Please visit W3School and Microsoft!
substr()
类似于 slice()。不同之处在于第二个参数规定被提取部分的长度,如果省略第二个参数,则该 substr() 将裁剪字符串的剩余部分。如果首个参数为负,则从字符串的结尾计算位置。
var str = "Apple, Banana, Mango";
var res = str.substr(7,6); //Banana
slice()
提取字符串的某个部分并在新字符串中返回被提取的部分。 该方法设置两个参数:起始索引(开始位置),终止索引(结束位置) 如果省略第二个参数,则该方法将裁剪字符串的剩余部分:
var str = "Apple, Banana, Mango";
var res = str.slice(7,13); // Banana
var str = "Apple, Banana, Mango";
var res = str.slice(-13,-7); // Banana
substring()
类似于 slice()。不同之处在于 substring() 无法接受负的索引。
search()
方法搜索特定值的字符串,并返回匹配的位置
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("name"); // 9
lastIndexOf()
方法返回指定文本在字符串中最后一次出现的索引,未找到文本返回 -1,接受作为检索起始位置的第二个参数
var str = "chinachina";
str.lastIndexOf("i"); // 7
indexOf()
方法返回字符串中指定文本首次出现的索引(位置),未找到文本返回 -1,接受作为检索起始位置的第二个参数
var str = "china";
str.indexOf("i"); // 2