JS中对于String数据类型的操作方法

1.concat

2.slice()、substr()、substring()

3.字符串位置方法

4.字符串包含方法

5.trim()方法

6.repeat()方法

7.padStart和padEnd()方法

8.字符串迭代与解构

9.字符串大小写转换

10.字符串模式匹配方法

11.localeCompare

一、concat

let stringValue='hello';
let result=stringValue.concat("world");
console.log(result);     //'hello world'
console.log(stringValue)    //"hello"

concat还能同时接受多个参数

let stringValue='hello';
let result=stringValue.concat('world','!');

console.log(result);   //'hello world!'
console.log(stringValue); 'hello'

二、slice()、substr()、substring()

slice()
第一个参数代表开始位置,第二个参数代表结束位置的下一个位置,截取出来的字符串的长度为第二个参数与第一个参数之间的差;若参数值为负数,则将该值加上字符串长度后转为正值;若第一个参数等于大于第二个参数,则返回空字符串.

substring()
第一个参数代表开始位置,第二个参数代表结束位置的下一个位置;若参数值为负数,则将该值转为0;两个参数中,取较小值作为开始位置,截取出来的字符串的长度为较大值与较小值之间的差.

substr()
第一个参数代表开始位置,第二个参数代表截取的长度

三个方法都返回调用他们的字符串的一个子字符串,而且都接收一个或者两个参数。第一个参数表示子字符串开始的位置,第二个参数表示子字符串结束的位置。对于slice()和substring()而言,第二个参数是提取结束的位置。对于substr而言,第二个参数表示返回的子字符串数量。任何情况下,省略第二个参数都意味着字符串末尾。与concat()方法一样,slice(),substr()和substring()也不会修改调用它们的字符串,而只会返回提取到的原始新字符串值,如下图所示。

let stringValue='hello world';
console.log(stringValue.slice(3));         //'lo world'
console.log(stringValue.substring(3));         //'lo world'   
console.log(stringValue.substr(3));         //'lo world'
console.log(stringValue.slice(3,7));         //'lo w'
console.log(stringValue.substring(3,7));    //'lo w'
console.log(stringValue.substr(3,7));         //'lo worl'

  当某个参数是负数时候,这3个方法的行为又有所不同,比如,slice()方法将所有负值参数都当成字符串长度加上负参数值。

  而substr()方法将第一个负参数值当成字符串长度加上该值,将第二个负参数值转换为0。substring()方法会将所有负参数值都转换为0.看下面例子

let stringValue='hello world';
console.log(stringValue.slice(-3));           //'rld'
console.log(stringValue.slice(-3));           //'hello world'
console.log(stringValue.slice(-3));           //'rld'
console.log(stringValue.slice(-3));           //'lo w'
console.log(stringValue.slice(-3));           //'hel'
console.log(stringValue.slice(-3));           //''(empty string)

 三、字符串位置方法

indexof()和lastIndexof()

两者方法的区别在于indexof()方法是从字符串开头开始查找字符串,而lastIndexof()方法从字符串末尾开始查找子字符串。来看下面例子:

let stringValue='hello world';
console.log(stringValue.indexof('o'));    //4
console.log(stringValue.lastIndexof('o'));    //7

这两个方法都可以接受可选的两个第二个参数,表示开始搜索的位置。这意味着,indexof()会从这个参数指定的位置开始向字符串末尾搜索,忽略该位置之前的字符。;lastIndexof()则会从这个参数指定位置开始向字符串开头搜索,忽略该位置之后到字符串末尾的字符。

复制代码
let stringValue='Lorem ipsum dolor sit amet,consectetur adipisicing elit';
let positions=new Array();
let pos=stringValue.indexof('e');
while(pos>-1){
  positions.push(pos);
  pos=stringValue.indexOf('e',pos+1);    

}
console.log(positions);   //[3,24,32,35,52]
复制代码

 四、字符串包含方法

Es6中增加了三个用于判断字符串中是否包含另一个字符串的方法:startWith()、endsWith()和includes()。这些方法都会从字符串中搜索传入的字符串,并返回一个表示是否包含的布尔值。它们的区别在于,startWith()检查开始于索引0的匹配项,endsWith()检查开始于索引(string.length-substring.length)的匹配项,而includes()检查整个字符串;

复制代码
let message='foobarbaz';
console.log(message.startsWith('foo'));    //true
console.log(message.startsWith('bar'));    //fa;se


console.log(message.endsWith('bar'));     //true
console.log(message.endsWith('bar'));     //false


console.log(message.includes('bar'));      //true
console.log(message.includes('qux'));      //false
复制代码

startsWith()和includes()方法接受可选的第二个参数,表示开始搜索的位置。如果传入第二个参数,则意味着这两个方法会从指定位置向着字符串末尾搜索,忽略该位置之前的所有字符。下面是一个例子

let message='foobarbaz';

console.log(message.startsWith('foo'));       //true
console.log(message.startsWith('foo',1));    //false

console.log(message.includes('bar'));         //true
console.log(message.includes('bar',4));      //false

endsWith()方法接收可选的第二个参数,表示应该当作字符串末尾的位置。如果不提供这个参数,那么默认就是字符串长度。如果提供这个参数,那么就好像字符串只有那么多字符一样;

let message='foobarbaz';
console.log(message.endsWith('bar'));     //false
ccnsole.log(message.endsWith('bar',6));   //true

 五、trim()方法

ES在所有字符串上都提供了trim()方法。这个方法会创建字符串的一个副本,删除前、后所有空格符,再返回结果。比如:

let stringValue='            hello world         ';

let trimmedStringValue=stringValue.trim();
console.log(stringValue);       //'hello world'
console.log(trimmedStringValue);  //'hello world'

六、repeat()方法

es在所有字符串上都提供了repeat()方法。这个方法接收一个整数参数,表示要将字符串复制多少次,然后返回拼接所有副本后的结果。

let stringValue='na';
console.log(stringValue.repeat(16)+'batman');

//  na   na  na  na  na  na  na  na  na  na  na  na  na  na  na batman

七、padStart()和padEnd()方法

padStart()和padEnd()方法会复制字符串,如果小于指定长度,则在相应一边填充字符,直至满足长度条件。这两个方法的第一个参数是长度。第二个参数是可选的填充字符串,默认为空格。

let stringValue='foo';
console.log(stringValue.padStart(6));   //'   foo'
console.log(stringValue.padStart(9,''.));   //'......foo'

console.log(stringValue.padEnd(6));   //'foo   '
console.log(stringValue.padEnd(9,''.));   //'foo......'

可选的第二个参数并不局限于一个字符,如果提供了多个字符的字符串,则会将其拼接并截取以匹配指定长度。此外,如果长度小于或者等于字符串长度,则会返回原始字符串。

八、字符串迭代与解构

字符串的原型上暴露一个@@iterator方法,表示可以迭代字符串的每个字符。可以像下面这样手动使用迭代器:

复制代码
let message='abc';
let stringIterator=message[Symbol.iterator]();

console.log(stringIterator.next());

console.log(stringIterator.next());    //{value:'a',done:false}
console.log(stringIterator.next());    //{value:'b',done:false}
console.log(stringIterator.next());    //{value:'c',done:false}
console.log(stringIterator.next());    //{value:undefined,done:true}
复制代码

在for-of循环中可以通过这个迭代器按序访问每个字符;

复制代码
for (const c of 'abcde'){
  console.log(c);  
}

//a
//b
//c
//d
//e
复制代码

有了迭代器之后,字符串就可以通过解构操作符来解构。比如,可以更方便地把字符串分割为字符数组:

九、字符串大小写转换

除了极少数地区语言(如土耳其语,)要使用特定的方法才能实现正确转换。

let stringValue='hello world';
console.log(stringValue.toLocaleUpperCase());   //'HELLO WORLD';
console.log(stringValue.toUpperCase());   //'HELLO WORLD';
console.log(stringValue.toLocaleLowerCase());   //''hello world';
console.log(stringValue.toLowerCase());   //''hello world';

这里,toLowerCase()和toLocaleLowerCase()都返回hello world ,而toUpperCase()和toLocaleUpperCase()都返回HELLO WORLD。通常,如果不知道代码涉及什么语言,则最好使用地区特定的转换方法。

 十、字符串模式匹配方法

String类型专门为在字符串中实现模式匹配设计了几个方法。第一个就是match()方法,这个方法本质上跟RegExp对象的exec()方法相同。match()方法接收一个参数,可以是一个正则表达式字符串,也可以是一个RegExp对象。来看下面的例子:

let text='cat,bat,sat,fat';
let pattern=/.at/;

//等价于pattern.exec(text)
let matches=text.match(pattern);
console.log(matches.index);      //0
console.log(matches[0]);          //'cat'
console.log(pattern.lastIndex);  //0

  match()方法返回的数组与RegExp对象的exec()方法返回的数组是一样的:第一个元素是与整个模式匹配的字符串,其余元素则是与表达式中的捕获组匹配的字符串。

  另一个查找模式的字符串方法是search()。这个方法唯一的参数与match()方法一样:正则表达式字符串或RegExp对象。这个方法返回模式第一个匹配的位置索引,如果没找到则返回-1.search()始终从字符串开头向后匹配模式。看下面的例子:

let text='cat,bat,sat,fat';
let pos=text.search(/at/);
console.log(pos);      //1

这里,search(/at/)返回1,即‘at’的第一个字符在字符串中的位置。为简化子字符串替换操作,ECMAScript提供了replace()方法。这个方法接收两个参数,第一个参数可以是一个RegExp对象或一个字符串(这个字符串不会转换为正则表达式),第二个参数可以是一个字符串或是一个函数。如果第一个参数是字符串,那么只会替换第一个子字符串。要想替换所有子字符串,第一个参数必须为正则表达式并且带全局标记,如下面的例子所示:

let text='cat,bat,sat,fat';
let result=text.replace('at','ond');
console.log(result);   //'cond,bat,sat,fat'
result=text.replace(/at/g,'ond');
console.log(result);    //'cond,bond,sond,fond'

使用这些特殊的序列,可以在替换文本中使用之前匹配的内容,如下面的例子所示:

let text='cat,bat,sat,fat';
result=text.replace(/(.at)/g,"word($1)');
console.log(result);     //word(cat),word(bat),word(sat),word(fat)

  这里,每个以'at'结尾的词都会被替换成’word‘后跟一对小括号,其中包含捕获组匹配的内容$1。replace()的第二个参数可以是一个函数。在只有一个匹配项时候,这个函数会收到3个参数:与整个模式匹配的字符串、匹配项在字符串中的开始位置,以及整个字符串。在有多个捕获组的情况下,每个匹配捕获组的字符串也会作为参数传给这个函数,但最后两个参数还是与整个模式匹配的开始位置和原始字符串。这个函数应该返回一个字符串,表示应该把匹配项替换成什么。使用函数作为第二个参数可以更细致地控制替换过程,如下所示:

 

复制代码
function htmlEscape(text){
  return text.replace(/[<>"&]/g,function(match,pos,originalText){
      switch(match){
          case "<":
              return "&lt;";
          case ">":
              return "&gt;";
          case "&":
              return "&amp;";
          case "\"":
              return "&quot;";
            
}      
})  
}

console.log(htmlEscape("<p class=\"greeting\">Hello world!</p>"))

//"&lt;p class=&quot;greeting&quot;&gt;Hello world!</p>"
复制代码

  这里,函数htmlEscape()用于将一段HTML中的4个字符替换成对应的实体:小于号、大于号、和号,还有双引号(都必须经过转义)。实现这个任务最简单的办法就是用一个正则表达式查找这些字符,然后定义一个函数,根据匹配的每个字符分别返回特定的HTML实体。

  最后一个与模式匹配相关的字符串方法是split()。这个方法会根据传入的分隔符将字符串拆分成数组。作为分隔符的参数可以是字符串,也可以是RegExp对象。(字符串分隔符不会被这个方法当成正则表达式。)还可以传入第二个参数,即数组大小,确保返回的数组不会超过指定大小。来看下面的例子:

let colorText="red,blue,green,yellow";
let colors1=colorText.split(",");         //['red','blue','green','yellow']
let colors2=colorText.split(",",2);         //['red','blue']
let colors3=colorText.split(/[^,]+/);         //["",",",",",",",""]

在这里,字符串colorText是一个逗号分割的颜色名称符串。调用split(",")会得到包含这些颜色名的数组,基于逗号进行拆分。要把数组元素限制为两个,传入第二个参数2即可。最后,使用正则表达式可以得到一个包含逗号的数组。注意在最后一次调用split()时候,返回的数组前后包含两个空字符串。这是因为正则表达式指定的分隔符出现在了字符串开头(“red”)和末尾(“yellow”)。

十一、localeCompare()方法

这个方法 比较两个字符串,返回如下3个值中的一个。

1.如果按照字母表顺序,字符串应该排在字符串参数前头,则返回负值(通常是-1,具体还要看与实际值相关的实现)

2.如果字符串与字符串参数相同,则返回0

3.如果按照字母表顺序,字符串应该排在字符串参数后头,则返回正值。(通常是1,具体还要看与实际值相关的实现)

let stringValue='yellow';
console.log(stringValue.localeCompare('brick)");           //1
console.log(stringValue.localeCompare('yellow)");           //0
console.log(stringValue.localeCompare('zoo)");           //-1

在这里,字符长‘yellow’与三个不同的值进行了比较:‘brick’、‘yellow’和‘zoo'。’brick‘按字母表顺序应该排在yellow前头,因此localeCompare()返回1.“yellow”等于“yellow”,因此“localeCompare()”返回0.最后,“zoo”在“yellow”后面, 因此“localeCompare()”返回-1.强调一下,因为返回的具体值可能因具体实现而异,所以最好像下面的示例中一样使用localeCompare();

复制代码
function determineOrder(value){
  let result=stringValue.localeCompare(value);
  if(result <0){
     console.log('The string 'yellow' comes before the string         
  ${value}`.);  
} else if(result > 0){
  console.log(`The string 'yellow' comes after the string ${value} .')  }
  else {
  console.log(`the string 'yellow' is equal to the string ${value}`);  
}  

}

determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");
复制代码

这样一来,就可以保证在所有实现中都能正确判断字符串的顺序了。

localeCompare()的独特之处在于,实现所在的地区(国家和语言)决定了这个方法如何比较字符串。在美国,英语是ES实现的标准语言,localeCompare()区分大小写,大写字母排在小写字母前面。但其他地区未必是这种情况。

 

posted @   Jaetyn  阅读(496)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示