当前位置:网站首页>The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends

The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends

2022-07-06 21:10:00 viceen

How to use strings startwith()- With XX start 、endsWith()- With XX ending 、trim()- Delete spaces at both ends

1、startsWith() Method

  • Used to determine whether the string starts with fixed data .
'abc'.startsWith('a')	//true
'abc'.startsWith('d')	//false
  • The method also has a second parameter , You can judge from the specified position of the string , The default is 0
'abcdefg'.startsWith('bcd'))	//false
'abcdefg'.startsWith('bcd',1))	//true

2、endsWith() Method

  • The second parameter specifies the length for the selected string
'abc'.endsWith('c') 	//true
'abc'.endsWith('bc') 	//true
'abc'.endsWith('a') 	//false
'abcdefg'.endsWith('def'))  //false
'abcdefg'.endsWith('def',6))    //true

3、trim() Method

  • From the original string The beginning and the end Delete the blank space , The space in the middle is not processed .
  • It does not affect the original string itself , Returns a new string .
'Testing'.trim() //'Testing'
' Testing'.trim() //'Testing'
' Testing '.trim() //'Testing'
'Testing '.trim() //'Testing'

example

<script>   
    var str = " yang ";
    console.log(str);// Output  yang 

    var str1 = str.trim();// There is a return value , To accept a value 
    console.log(str1);// Output yang ( There are no spaces )

    var str2 = "ya ng";
    console.log(str2);// Output "ya ng"
    var str3 = str2.trim();
    // From a string of ** Both ends ** Delete white space characters . The space in the middle of the string will not be deleted 
    console.log(str3);// Output "ya ng"
</script>
Use regular expressions to realize string trim Method
String.prototype._trim = function() {
    
  return this.replace(/^(\s*)|(\s*)$/g, '')
}
var str = ' ssss '
console.log(str)  //  ditto 
console.log(str.length)  // 11

var strNew = str._trim()
console.log(strNew)  // 'ssss'
console.log(strNew.length)  // 4
  • there * Represents a match 0 One or more ,
  • At this point, we need to consider two situations , One is that there is a space in front , The other is that there is a space after . So we use | To match .
  • And use replace To replace it , Only the first one will be replaced , So we need to add global matching g.
原网站

版权声明
本文为[viceen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061250444764.html

随机推荐