Javascript的字符串的操作方法

1、indexOf():从数组的开头(位置0)开始向后查找。lastIndexOf():从数组的末尾开始向前查找。这两个方法都返回的是要查找的项在数组中的位置下标值,在没有找到的情况下返回的是-1。

var numbers=[1,2,3,4,5,4,3,2,1];

console.log(numbers.indexOf(4)); //3

console.log(numbers.lastIndexOf(4)); //5

console.log(numbers.indexOf(4,4)); //5

console.log(numbers.lastIndexOf(4,4));//3

2、slice():提取字符串的某个部分,并返回一个新字符串。slice()方法可以接受一个参数或者两个参数。在一个参数的情况下,slice()方法返回的是从该参数指定位置开始到当前结束位置。如果有两个参数,则返回的是起始位置和结束位置之间的字符串,但不包括结束位置的字符。

var str=”hello world”;

console.log(str.slice(3)); //lo world

console.log(str.slice(3,7)); //lo w

3、split():用于把一个字符串分割成字符串数组。

var str=”hello world”;

console.log(str.split(“ “)); //[“hello”, “world”]

console.log(str.split(“-“)); //[“hello world”]

var num=”1-2-3-4-5-6-7-8”;

console.log(num.split(“-“))//[“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”]

4、substring():提取相应区间的字符,可以有一个参数或者两个参数。在一个参数的情况下,substring()方法返回的是从该参数指定位置开始到当前结束位置。如果有两个参数,则返回的是起始位置和结束位置之间的字符串,但不包括结束位置的字符。与slice()很相似。
var str=”hello world”;

console.log(str.slice(3)); //lo world

console.log(str.slice(3,7)); //lo w
4、toUpperCase():把字符串转换成大写。toLowerCase():把字符串转换成小写的。
var str=”hello world”;

console.log(str.toUpperCase()); //HELLO WORLD

console.log(str.toLowerCase()); //hello world