JS-字符串常用API

常用API

检索

  • index of()

检索子串首次出现的下标,没有该子串则返回-1
①indexof(substr)
var str ="In order to be irreplaceable one must always be different";
var substr="order";
var id = str.indexOf(substr);
console.log(id);//输出3
②indexof(substr,15)
从15号位开始检索be首次出现的下标
console.log(str.indexOf("be",15));//输出45

  • lastIndexOf()

检索子串最后一次出现的下标
str ="In order to be irreplaceable one must always be different";
var strId = str.indexOf("be");
console.log(strId);//输出12
console.log(str.indexOf("be",strId + 1));//输出45

console.log(str.lastIndexOf("be"));//输出45
  • includes()

检索子串是否存在(区分大小写)
var str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false

替换

  • replace(str1,str2)

     把字符串中值中找到的第一个str1替换为str2,不会改变调用它的字符串值,返回一个被替换后的新字符串
var str = "To be, or not to be, that is the question.";
console.log(str.replace("be","is")) ;
//In order to is irreplaceable one must always be different

console.log(
        str.replace(
          "dog",


          /*
          将sub重复10次
          sub为找到的第一个子串
          返回一个新的子串 替换sub
          */
          function (sub) {
            console.log("sub=", sub);


            let newSub = "";
            for (var i = 0; i < 10; i++) {
              newSub += sub;
            }


            return newSub;
          }
        )
      );

  • replaceAll()

   把字符串中值中找到的 全部str1替换为str2,不会改变调用它的字符串值,返回一个被替换后的新字符串
//将所有的脏话替换为*
        var str ="你烧饼你就是大烧饼";
        var word = "烧饼";


        function shield(str,word){
           return str.replaceAll(word,"**");
        }


        console.log(shield(str,word));//输出你是**你就是大**


截取

  • substring(start,end) (包括start,不包括end)

返回索引start和索引end之间的部分
  • substring(start)

返回索引start到字符串的末尾之间的部分
  • split()

  将字符串划分为子串数组,返回该数组
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"
  • slice( begin, end)

提取字符串的一部分并将其作为新字符串返回,而不修改原始字符串
注:begin值为负数则从字符串后面开始数,省略end则一直提取到字符串末位
slice( begin)
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// expected output: "the lazy dog."
  • trim()

  返回一个将str开头和结尾的空格都去掉的字符串

判断

判断str是否以指定子串开头或结尾,是则返回true,否则返回false
  • startsWith()

  • endsWith()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值