字符串常用方法

字符串常用方法

在这里,我们讲述一下string的常见方法,在我们时机开发中,字符串的使用评率是很高的,所以这些常见的方法我们需要记住并且熟练运用。下面我们就来了解字符串有哪些常用的方法吧!

注意:

由于字符串的不可变性,所以字符串的所有方法都是返回一个新的字符串,而不是修改原来的字符串。(原来的字符串不变)

查找字符串

indexOf()

value = str.indexOf('要查找的字符串',[查找开始的位置(索引)]);

这个方式是从字符串索引号[0]开始向后面查找,如果找到了,就返回第一个字符的索引号(不会继续向后查找),如果没有找到,就返回-1。

这个方法后面那个查找开始位置为可选参数,如果我们不填写,默认是从索引号[0]开始查找。

那么:

  • 如果查找结果返回的是0,说明我们要查找的参数位于字符串的开头。
  • 如果查找结果返回的是-1,说明我们要查找的参数在字符串里面不存在。

栗子时间:

var str = 'hello world';
console.log(str.indexOf('hello')); // 0
console.log(str.indexOf('world')); // 6
console.log(str.indexOf('o',5)); // 7
console.log(str.indexOf('world',7)); // -1

lastIndexOf()

value = str.lastIndexOf('要查找的字符串',[查找开始的位置(索引)]);

这个方法是从字符串的最后一个字符开始向前面查找,如果找到了,就返回第一个字符的索引号(不会继续向前查找),如果没有找到,就返回-1。

这个方法后面那个查找开始位置为可选参数,如果我们不填写,默认是从索引号[0]开始查找。

那么:

  • 如果查找结果返回的是0,说明我们要查找的参数位于字符串的开头。
  • 如果查找结果返回的是-1,说明我们要查找的参数在字符串里面不存在。

栗子时间:

var str = 'hello world';
console.log(str.lastIndexOf('hello')); // 0
console.log(str.lastIndexOf('world')); // 6
console.log(str.lastIndexOf('o',6)); // 4
console.log(str.lastIndexOf('world', 7)); // 6

进阶

  • 通过前面的学习,我们知道了indexOf()lastIndexOf()这两个方法,那么我们就可以通过这两个方法来判断一个字符串是否包含另一个字符串了。

    var str = ‘hello world’;
    if(str.indexOf(‘hello’) != -1){
    console.log(‘包含’);
    }else{
    console.log(‘不包含’);
    }

  • indexOf()lastIndexOf()有一个缺点:它只能返回查找到的第一个字符的索引号,如果我们要查找的字符串在字符串里面出现了多次,那么我们就无法得到它的索引号了。那么我们就可以通过循环的方法来解决这个问题。

    var str = ‘hello world oo’;
    var q = str.indexOf(‘o’);
    while (q <= str.length) {
    if (str.indexOf(‘o’, q) != -1) {
    q = str.indexOf(‘o’, q);
    console.log(‘o’ + q); // 4
    } else {
    break;
    }
    q++;
    }

value = str.search('要查找的字符串');

这个方法是用来查找字符串里面是否包含另一个字符串的,如果找到了,就返回第一个字符的索引号(不会继续向后查找),如果没有找到,就返回-1。

include()

value = str.include('要查找的字符串',[position]);

这个方法是用来查找字符串里面是否包含另一个字符串的,如果找到了,就返回true,如果没有找到,就返回false。

参数中的position,代表我们检索开始的位置,如果不填写,默认是从索引号[0]开始检索;如果指定就从指定位置开始检索。

let str = 'hello world';
console.log(str.include('hello')); // true
console.log(str.include('world')); // true

console.log(str.include('hello',1)); // false
console.log(str.include('world',7)); // false

startsWith()&endsWith()

value = str.startsWith('要查找的字符串',[position]);

value = str.endsWith('要查找的字符串',[position]);

这两个方法是用来判断字符串是否以指定的字符串开头或结尾的,如果是,就返回true,如果不是,就返回false。

注意:

这个两个方法中的position参数意义是不同的:

  • startsWith()中的position代表我们检索开始的位置,如果不填写,默认是从索引号[0]开始检索,直到字符串末尾;如果指定就从指定位置开始检索,直到字符串末尾。[position,字符串末尾]

  • endsWith()中的position代表我们检索结束的位置,如果不填写,默认是从字符串末尾开始检索,直到索引号[0];如果指定就从指定位置开始检索,直到索引号[0]。[0,position)

    let str = ‘hello world’;
    console.log(str.startsWith(‘hello’)); // true
    console.log(str.startsWith(‘world’)); // false

    console.log(str.endsWith(‘hello’)); // false
    console.log(str.endsWith(‘world’)); // true

    console.log(str.startsWith(‘hello’,1)); // false
    console.log(str.startsWith(‘world’,7)); // false

    console.log(str.endsWith(‘hello’,1)); // false
    console.log(str.endsWith(‘world’,7)); // false