文章目录
常用的字符串操作方法
1、charAt() / charCodeAt()
charAt(index)
方法从一个字符串中返回指定的字符,如果没有返回空
var str = “HELLO WORLD”;
str.charAt(0); // 返回 H
charCodeAt ()
方法是获取指定位置字符的Unicode编码
2、indexOf()
indexOf
(‘需要查找的字符’) 方法返回字符串中指定文本首次出现的索引(位置)
var str = “The full name of China is the People’s Republic of China.”;
var pos = str.indexOf(“China”);
3、lastIndexOf()
JavaScript 从零计算位置。
0 是字符串中的第一个位置,1 是第二个,2 是第三个 …lastIndexOf()
方法返回指定文本在字符串中最后一次出现的索引
var str = “The full name of China is the People’s Republic of China.”;
var pos = str.lastIndexOf(“China”);
4、slice()
stringObject.slice(start,end)
截取字符串。
该方法设置两个参数:
start:(必须)指定子字符串的开始位置。
end:(可选)表示子字符串到哪里结束,end本身不在截取范围之内,省略不写时候直接截取至字符串末尾。
如果某个参数为负,则从字符串的结尾开始计数。
5、substring()
语法及功能同slice()完全一样,区别只在于遇到负数时,自动将参数转换为0。
substring()
会把较小的数作为开始位置,较大的数作为结束位置。
6、substr()
stringObiect.substr(start,length)
截取字符串
start :(必需)指定字符串的开始位置;
length:(可选)表示截取的字符长度,省略时截取至字符串的末尾。
当start为负数时,会将传入的负值与字符串的长度相加。
当len为负数时返回空字符串。
7、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”]
8、replace()
replace("被替换的值",“新的值”)
: 在字符串中用一些字符替换另一些字符,只能替换第一个不能替换全部
str = “Please visit Microsoft and Microsoft!”;
var n = str.replace(“Microsoft”, “W3School”);
9、concat()
concat()
: 连接两个或多个字符串:
var text1 = “Hello”;
var text2 = “World”;
text3 = text1.concat(" ",text2); //Hello World
10、trim()
trim()
:去掉字符串首尾空格
var str = " Hello World! ";
alert(str.trim());
Internet Explorer 8 或更低版本不支持 trim() 方法。
如需支持 IE 8,您可搭配正则表达式使用 replace() 方法代替
11、toUpperCase()
将字符串转换为大写
返回值:返回一个新字符串,不修改原字符串
11、toLowerCase()
将字符串转换为小写
返回值:返回一个新字符串,不修改原字符串