JavaScript常用字符串操作方法

1、concat() 

concat() 方法用于连接两个或多个字符串,并返回连接后的字符串。stringObject.concat() 与 Array.concat() 很相似。

var str1="Hello "
var str2="world!"
console.log(str1.concat(str2)) //Hello world!

2、indexOf 和 lastIndexOf

都接受两个参数:查找的值、查找起始位置
不存在,返回 -1 ;存在,返回位置。indexOf 是从前往后查找, lastIndexOf 是从后往前查找。
indexOf

var a = [2, 9, 9];
a.indexOf(2); // 0
a.indexOf(7); // -1

if (a.indexOf(7) === -1) {}
lastIndexOf
var numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3
numbers.lastIndexOf(7); // -1
numbers.lastIndexOf(2, 3); // 3
numbers.lastIndexOf(2, 2); // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3

3、substring() 和 substr()

相同点:如果只是写一个参数,两者的作用都一样:都是是截取字符串从当前下标以后直到字符串最后的字符串片段。

substr(startIndex);
substring(startIndex);
var str = '123456789';
console.log(str.substr(2)); // "3456789"
console.log(str.substring(2)) ;// "3456789"

不同点:第二个参数

substr(startIndex,lenth): 第二个参数是截取字符串的长度(从起始点截取某个长度的字符串);
substring(startIndex, endIndex): 第二个参数是截取字符串最终的下标 (截取2个位置之间的字符串,‘含头不含尾’)。
console.log("123456789".substr(2,5)); // "34567"
console.log("123456789".substring(2,5)) ;// "345"

4、toLowerCase()

toLowerCase()把字符串转换为小写。

var str="HELLO WORLD!"
console.log(str.toLowerCase());//hello world!

5、toUpperCase()

toUpperCase() 把字符串转换为大写。

var str="hello world!"
console.log(str.toUpperCase() );//HELLO WORLD!

猜你喜欢

转载自www.cnblogs.com/ycg-myblog/p/10373876.html