js 常用字符串操作方法总结

前言:
刚刚把数组方法总结完,继续总结一下字符串方法,方便自己以后查看,也希望可以帮到其他小伙伴哟~

字符方法:

charAt(index) & charCodeAt(index)

定义: 返回指定索引的字符/unicode编码

var str="hello world"; 
console.log(str.charAt(1));//e 
console.log(str.charCodeAt(1));//101 
//还可以使用方括号加数字索引来访问字符串中特定的字符 
console.log(str[1]);//e 

字符串方法:

1. split() - 字符串分割成数组

定义:把一个字符串分割成字符串数组(不改变原字符串)
语法:str.split(seperator, limit)
参数:
seperator(可选),指定字符串或正则
limit(可选),指定数组的最大长度

var myStr = "I,Love,You,Do,you,love,me";

var substrArray = myStr.split(",");
// ["I", "Love", "You", "Do", "you", "love", "me"];

var arrayLimited = myStr.split(",", 3);
// ["I", "Love", "You"];

2. 截取字符串

str.substring(start, end)
两个参数都为正数,返回值:[start,end) 也就是说返回从start到end-1的字符

str.slice(start, end)
两个参数可正可负,负值代表从右截取,返回值:[start,end) 也就是说返回从start到end-1的字符

str.substr(start, length)
start参数可正可负,负数代表从右截取

注:

  • 这三个方法都会返回被操作字符串的一个子字符串,都接收一或两个参数 。
  • 如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。这些方法也不会修改字符串本身,只是返回一个基本类型的字符串值。
  • 除了 slice() 和 substr() 方法里的负值是代表从右截取,其他方法里的负值一律作为0处理。
var str="hello world"; 
console.log(str.slice(3));//lo world 
console.log(str.substring(3));//lo world 
console.log(str.substr(3));//lo world 
console.log(str.slice(3,7));//lo w  7表示子字符串最后一个字符后面的位置  简单理解就是包含头不包含尾 
console.log(str.substring(3,7));//lo w 
console.log(str.substr(3,7));//lo worl 7表示返回7个字符 

console.log(str.slice(3,-4));//lo w  -4+11=7表示子字符串最后一个字符后面的位置  简单理解就是包含头不包含尾 
console.log(str.substring(3,-4));//hel  会转换为console.log(str.substring(3,0)); 
//此外由于这个方法会将较小数作为开始位置,较大数作为结束位置,所以相当于调用console.log(str.substring(0,3)); 
console.log(str.substr(3,-4));//""空字符串 
console.log(str.substring(3,0)); //hel

3. 查找字符串

str.indexOf(searchString, startIndex)
返回子字符串第一次出现的位置,从startIndex开始查找,找不到时返回-1

str.lastIndexOf(searchString, startIndex)
从右往左查找子字符串,找不到时返回-1

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

4. 字符串大小写转换

toUpperCase() : 将所有字符串转换成大写
toLowerCase() : 将所有字符串转换成小写

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

5. 字符串替换

str.replace(rgExp/substr, replaceText) : 返回替换后的字符串

var str="cat,bat,sat,fat"; 
var res=str.replace("at","one");//第一个参数是字符串,所以只会替换第一个子字符串 
console.log(res);//cone,bat,sat,fat 

var res1=str.replace(/at/g,"one");//第一个参数是正则表达式,所以会替换所有的子字符串 
console.log(res1);//cone,bone,sone,fone 

6. 字符串拼接

str.concat(str1, str2)

var str="hello "; 
var res=str.concat("world"); 
console.log(res);  //hello world 
console.log(str);  //hello  这说明原来字符串的值没有改变 
var res1=str.concat("nihao","!"); 
console.log(res1);  //hello nihao!  说明concat方法可以接收任意多个参数 
//虽然concat方法是专门用来拼接字符串的,但是实践中我们使用最多的还是加操作符+,因为其简易便行

7. 去掉字符串首尾空格

str.trim():用来删除字符串前后的空格

var str="   hello world   "; 
console.log('('+str.trim()+')');  //(hello world) 
console.log('('+str+')');  //(   hello world   )

8. 字符串模式匹配

match():只接受一个参数,由字符串或RegExp对象指定的一个正则表达式
search():只接受一个参数,由字符串或RegExp对象指定的一个正则表达式

search方法返回字符串中第一个匹配项的索引,如果没有匹配项,返回-1

var str="cat,bat,sat,fat"; 
var pattern=/.at/; 
var matches=str.match(pattern); 
console.log(matches.index);//0 
console.log(matches[0]);//cat 
console.log(pattern.lastIndex);//0 
//lastIndex表示开始搜索下一个匹配项的字符位置,从0算起 
var pos=str.search(/at/); 
console.log(pos);//1 1表示at字符串在原来字符串中第一次出现的位置 

9. 字符串比较

str.localeCompare(str1):比较两个字符串

  • 如果字符串在字母表中应该排在字符串参数之前,则返回一个负数
  • 如果字符串等于字符串参数,则返回0
  • 如果字符串在字母表中应该排在字符串参数之后,则返回一个正数
var str="yellow"; 
console.log(str.localeCompare("brick")); //1 
console.log(str.localeCompare("yellow")); //0 
console.log(str.localeCompare("zoo")); //-1 

10. fromCharCode方法

str.fromCharCode(字符编码):接收一或多个字符编码,然后将其转换为字符串

fromCharCode方法是String构造函数的一个静态方法

console.log(String.fromCharCode(104,101,108,108,111));//hello 

综合示例

示例一:找到匹配字符串所在的各个位置

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串匹配</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /*找到匹配字符串所在的各个位置*/
    var str="asadajhjkadaaasdasdasdasd"; 
    var position=[]; 
    var pos=str.indexOf("d"); 
    while(pos>-1){ 
      position.push(pos); 
      pos=str.indexOf("d",pos+1); 
    } 
    console.log(position);//[3, 10, 15, 18, 21, 24] 
  </script> 
  </body> 
</html>

示例二:字符串去重

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串去重</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  //String.split() 执行的操作与 Array.join 执行的操作是相反的 
  //split() 方法用于把一个字符串分割成字符串数组。 
  //join方法用于将字符串数组连接成一个字符串 
  //如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。 
    var str="aahhgggsssjjj";//这里字符串没有可以分隔的字符,所以需要使用空字符串作为分隔符 
    function unique(msg){ 
      var res=[]; 
      var arr=msg.split(""); 
      //console.log(arr); 
      for(var i=0;i<arr.length;i++){ 
        if(res.indexOf(arr[i])==-1){ 
          res.push(arr[i]); 
        } 
      } 
      return res.join(""); 
    } 
    console.log(unique(str));//ahgsj 
  </script> 
  </body> 
</html>

示例三:判断字符串中字符出现的次数

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串操作</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /* 
  1.先实现字符串去重 
  2.然后对去重后的数组用for循环操作,分别与原始数组中各个值进行比较,如果相等则count++,循环结束将count保存在sum数组中,然后将count重置为0 
  3.这样一来去重后的数组中的元素在原数组中出现的次数与sum数组中的元素是一一对应的 
   */
    var str="aacccbbeeeddd"; 
    var sum=[]; 
    var res=[]; 
    var count=0; 
    var arr=str.split(""); 
    for(var i=0;i<arr.length;i++){ 
      if(res.indexOf(arr[i])==-1){ 
        res.push(arr[i]); 
      } 
    } 
    for(var i=0;i<res.length;i++){ 
      for(var j=0;j<arr.length;j++){ 
        if(arr[j]==res[i]){ 
          count++; 
        } 
      } 
      sum.push(count); 
      count=0; 
    } 
    console.log(res);//["a", "c", "b", "e", "d"] 
    for(var i=0;i<res.length;i++){ 
      var str=(sum[i]%2==0)?"偶数":"奇数"; 
      console.log(res[i]+"出现了"+sum[i]+"次"); 
      console.log(res[i]+"出现了"+str+"次"); 
    } 
  </script> 
  </body> 
</html>

阿里面试 - 字符串操作

<script type="text/javascript"> 
  var str = "www.taobao.com"; 
  var res = str.split("").reverse().join("").replace('oat',''); 
  console.log(res);//moc.oab.www 
</script>

附上参考链接:https://www.jb51.net/article/97915.htm

  • 6
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaScript提供了许多字符串操作方法,以下是一些常用的方法: 1. 字符串长度:使用`length`属性可以获取字符串的长度。 示例:`var str = "Hello World"; console.log(str.length); // 输出 11` 2. 字符串连接:使用`+`运算符可以将两个字符串连接起来。 示例:`var str1 = "Hello"; var str2 = "World"; console.log(str1 + " " + str2); // 输出 "Hello World"` 3. 字符串索引:可以通过索引访问字符串中的单个字符,索引从0开始。 示例:`var str = "Hello"; console.log(str); // 输出 "H"` 4. 子字符串提取:使用`substring(start, end)`方法可以提取字符串的子串,其中`start`表示起始索引(包含),`end`表示结束索引(不包含)。 示例:`var str = "Hello World"; console.log(str.substring(0, 5)); // 输出 "Hello"` 5. 字符串查找:使用`indexOf(substring)`方法可以查找子串在字符串中的位置,返回第一次出现的索引,如果没有找到则返回-1。 示例:`var str = "Hello World"; console.log(str.indexOf("World")); // 输出 6` 6. 字符串替换:使用`replace(oldValue, newValue)`方法可以将字符串中的指定子串替换为新的子串。 示例:`var str = "Hello World"; console.log(str.replace("World", "CSDN")); // 输出 "Hello CSDN"` 7. 字符串分割:使用`split(separator)`方法可以将字符串按照指定的分隔符分割成数组。 示例:`var str = "Hello,World"; console.log(str.split(",")); // 输出 ["Hello", "World"]` 8. 字符串大小写转换:使用`toUpperCase()`方法可以将字符串转换为大写,使用`toLowerCase()`方法可以将字符串转换为小写。 示例:`var str = "Hello World"; console.log(str.toUpperCase()); // 输出 "HELLO WORLD"`

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值