string commonly used api

match、exec

  • String.prototype.match
  • RegExp.prototype.exec
  1. Without adding g, the return value of both is the same.
var str = 'asd123lkj789qwe';
var reg = /\d/;
console.log(str.match(reg))//['1', index: 3, input: 'asd123lkj789qwe', groups: undefined]
console.log(reg.exec(str)) //['1', index: 3, input: 'asd123lkj789qwe', groups: undefined]
  1. Add g, match returns an array, and exec has a memory function.
var reg = /\d/g;
console.log(str.match(reg))//(6) ['1', '2', '3', '7', '8', '9']

// exec+g 有了记忆功能
console.log(reg.exec(str)) //['1', index: 3, input: 'asd123lkj789qwe', groups: undefined]
console.log(reg.exec(str)) //['2', index: 4, input: 'asd123lkj789qwe', groups: undefined]
// 直到返回null,然后再从头开始匹配

charAt、charCodeAt、fromCharCode

var str = 'a';
console.log(str.charAt(0));//a
console.log(str.charCodeAt());//97

console.log(String.fromCharCode('97'));//a
  • fromCharCode prints 26 letters
for(var i =0,res='';i<26;i++){
    
    
    res+=String.fromCharCode(65+i)
}
console.log(res)
// ABCDEFGHIJKLMNOPQRSTUVWXYZ

var res = new Array(26).fill('').reduce((pre,item,index)=>{
    
    
    return pre + String.fromCharCode(65+index)
},'')
console.log(res)
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
var res = new Array(60).fill('').reduce((pre,item,index)=>{
    
    
    return pre + String.fromCharCode(65+index)
},'').match(/[A-Za-z]/gm).join('')
console.log(res)
// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

toLocaleLowerCase、toLocaleUpperCase、toLowerCase、toUpperCase

String.prototype.toLocaleLowerCase
String.prototype.toLocaleUpperCase
// 上面是下面的超集合,外国语建议使用上面的
String.prototype.toLowerCase
String.prototype.toUpperCase

Deprecated style tags

// 废弃的样式标签
var str = 'test style';
str.fontcolor('red') //'<font color="red">test style</font>'
str.sub() //'<sub>test style</sub>'
str.sup()
str.fixed() //'<tt>test style</tt>'
str.bold() //'<b>test style</b>'

substring、substr

// substring
// 1. substring支持倒序
console.log(str.substring(3,1)) //23
console.log(arr.slice(3,1)) //[]
// 2. 负数看做0
console.log(str.substring(-2)) //12345
  • If the slice parameter is a negative number, it is treated as strLength + the negative number

  • substring extracts characters from indexStart to indexEnd (exclusive). In particular:

    1. If indexStart equals indexEnd, substring returns an empty string.
    2. If indexEnd is omitted, substring extracts characters up to the end of the string.
    3. If any parameter is less than 0 or NaN, it is treated as 0.
    4. If any parameter is greater than stringName.length, it is treated as stringName.length.
    5. If indexStart is greater than indexEnd, the execution effect of substring is as if the two parameters are swapped. See example below.
  • str.substr(start[, length])

    1. If start is a negative number, it is treated as strLength + start
    2. If start is negative and abs(start) is greater than the length of the string, substr uses 0 as the index to start extracting.
    3. The processing of negative numbers is the same as slice
    4. If length is 0 or negative, substr returns an empty string. If length is omitted, substr extracts characters up to the end of the string.
      This method is deprecated.
      substr is not part of the core JavaScript language and may be removed in the future. If possible, use substring() instead

Methods with the same name for strings and arrays

slice

  • slice behaves the same on strings and arrays
var arr = [1,2,3,4,5];
var str = '12345';

console.log(arr.slice(1))  //从索引1到末尾   (4) [2, 3, 4, 5]
console.log(arr.slice(1,3)) //区间左闭右开[) (2) [2, 3]

console.log(arr.slice(NaN))
console.log(arr.slice(null))//NaN null 无效参数=>0
console.log(arr.slice(0))//(5) [1, 2, 3, 4, 5]

console.log(arr.slice())  //(5) [1, 2, 3, 4, 5]
console.log(arr.slice(undefined))//undefined相当于没有传参数

console.log(arr.slice(-2))  //arr.length + -2 = 3 => arr.slice(3) [4, 5]

console.log(arr.slice([1])) // [2, 3, 4, 5] 会做Number的隐式转换
console.log(arr.slice('1')) // [2, 3, 4, 5]

indexof、lastIndexof

  • str.indexOf(searchValue [, fromIndex])
  • arr.indexOf(searchElement[, fromIndex])
// indexof 是 全等===
var arr = [1,2,3,4,5];
var str = '12345'
console.log(arr.indexOf(3)) //2
console.log(str.indexOf(3)) //2

str.indexOf(4)
str.indexOf('4')
str.indexOf([4])
// 都是3

str.indexOf(1,-2)//0 字符串把负数或不合理的值null undefined NaN当做0是一种通用方式
  • str.lastIndexof

undefined NaN = > length-1

var str = '1623465'
console.log(str.lastIndexOf(6,NaN));
console.log(str.lastIndexOf(6,undefined));
console.log(str.lastIndexOf(6,str.length-1));//=>str.lastIndexOf(6,NaN)
console.log(str.lastIndexOf(6))
// 都是5
console.log(str.lastIndexOf(6,null)); //-1 null看作0

includes

replace

  • str.replace(regexp|substr, newSubStr|function)

  • This method does not change the string itself, but just returns a new replaced string.

  • regexp (pattern)
    a RegExp object or its literal. The content matched by this regular expression will be replaced by the return value of the second parameter.

    var str = 'plusplus'
    str.replace(/plus/,'+') //'+plus'
    //正则+g 全局匹配
    str.replace(/plus/g,'+') //'++'
    
  • substr (pattern)
    A string that will be replaced by newSubStr. It is treated as a whole string, not a regular expression.
    Only the first match is replaced .

    var str = 'plusplus'
    str.replace('plus','+') //'+plus'
    
  • newSubStr->replacement string can insert the following special variable names:

    • $$ inserts a "$".

    • $& inserts the matching substring.

    • $` Inserts the content to the left of the currently matched substring.

    • $' inserts the content to the right of the currently matched substring.

    • $nIf
      the first parameter is a RegExp object and n is a non-negative integer less than 100, then insert the nth bracket-matching string. Tip: Indexing starts from 1. If the nth group does not exist, the matching content will be replaced with a literal. For example, if the third group does not exist, the matched content will be replaced with "$3".

    • $<Name>
      Here Name is a group name. If there is no grouping (or no match) in the regular expression, this variable will be treated as an empty string. Only available in browsers that support named group capture.

  • Swapping two words in a string
    The following example demonstrates how to swap the positions of two words in a string. This script uses $1 and $2 instead of replacement text.

    var re = /(\w+)\s(\w+)/g;
    var str = "John Smith";
    //str.match(re) //['John Smith']
    var newstr = str.replace(re, "$2, $1");
    // Smith, John
    console.log(newstr);
    
    var re = /(\w+)\s(\w+)/g;
    var str = "John Smith";
    //str.match(re) //['John Smith']
    var newstr = str.replace(re, function($,$1,$2){
          
          
        // $,$1,$2 参数名可以为其他名字 
        //$1,$2 代表第一个二个子表达式
        console.log($,$1,$2);
        return $2+' '+$1
    });
    // Smith, John
    console.log(newstr); //Smith John
    
  • Make it uppercase

    var str = 'js-plus-plus'
    var reg = /-(\w)/g ///-\w/g
    var str1 = str.replace(reg,function($,$1){
          
          
        console.log($,$1) //$1是子表达式
        return $1.toUpperCase()
    })
    console.log(str1) //jsPlusPlus
    
  • change to underline

    var str = 'jsPlusPlus'
    var reg = /([A-Z])/g ///-\w/g
    //str.match(reg) //['P', 'P']
    var str1 = str.replace(reg,function($,$1){
          
          
        console.log($,$1) //$1是子表达式
        return '-'+$1.toLowerCase()
    })
    console.log(str1) //js-plus-plus
    
  • xxyyzz->XxYyZz

    //1. 
    var str = 'xxyyzz'
    var reg = /(\w)\1(\w)\2(\w)\3/g
    //str.match(reg) //['xxyyzz']
    var str1 = str.replace(reg,function($,$1,$2,$3){
          
          
        return $1.toUpperCase() + $1 
            + $2.toUpperCase() + $2
            + $3.toUpperCase() + $3
    })
    console.log(str1) //XxYyZz
    
    //2. 
    var str = 'xxyyzz'
    var reg = /(\w)\1/g
    //str.match(reg) //['xxyyzz']
    var str1 = str.replace(reg,function($,$1){
          
          
        return $1.toUpperCase() + $1
    })
    console.log(str1) //XxYyZz
    
  • Match regular symbols

    var str = 'aa\\bb\\cc' //'aa\bb\cc'
    // var reg = /\/; //语法错误 要匹配正则语法中的转义字符需要转移
    var reg = /\\/g; //
    str.match(reg) //(2) ['\', '\']
    
  • Remove duplicates

    var str = 'aaabbbbbcccccc'
    str.replace(/(\w)\1*/g,'$1') //'abc'
    str.match(/(\w)\1*/g) //(3) ['aaa', 'bbbbb', 'cccccc']
    
  • Divide the number zero into three digits

    var str = '10000'
    str.replace(/(000)/g,'$1,') //'1000,0'
    
  • Divide numbers by three digits

    var str = '123456789'
    str.replace(/(\d\d\d)/g,'$1,') //'123,456,789,'
    //非单词边界的判断
    var str = '123456789'
    str.replace(/(\d\d\d)\B/g,'$1,') //'123,456,789'
     //
    var str = '1234567890'
    //str.match(/(?=(\B)(\d{3})+$)/g) //(3) ['', '', '']
    str.replace(/(?=(\B)(\d{3})+$)/g,'$1,') //'1,234,567,890'
    // 以空字符为主体,到末尾结束,中间三个数字为一组出现了一次或多次
    // 找到符合条件的空字符+逗号
    // '1234567890'.replace(/(?=(\B)(\d{3})+$)/g,',')
    // 不匹配开头边界出的字符
    
  • match start

    'abcdef'.replace(/(?=(\b\w+))/g,'1')
    
  • Matching of double brace templates

    var str = 'My name is {
          
          {name}}, I\'m {
          
          {age}} years old'
    // var reg = /{
          
          {.*}}/g // ["{
          
          {name}}, I'm {
          
          {age}}"] 贪婪匹配
    // var reg = /{
          
          {.*?}}/g // ['{
          
          {name}}', '{
          
          {age}}'] 加?是为了非贪婪匹配
    var reg = /{
           
           {(.*?)}}/g  子表达式
    str.match(reg) 
    var str1 = str.replace(reg,function(node,key){
          
          
        console.log(node,key) 
        // {
          
          {name}} name
        // {
          
          {age}} age
        return {
          
          
            name:'Jenny',
            age:26
        }[key]
    })
    // (2) ['{
          
          {name}}', '{
          
          {age}}']
    // "My name is Jenny, I'm 26 years old"
    
  • HTML template replacement

    <!DOCTYPE html>
    <html lang="en">
    <body>
        <div id="wrap">
            <h1>{
         
         {title}}</h1>
            <p>{
         
         {content}}</p>
        </div>
    </body>
    <script>
        var dom = document.getElementById("wrap");
        var reg = /{
             
             {(.*?)}}/g 
        var str1 = dom.innerHTML.replace(reg,function(node,key){
            
            
            return {
            
            
                title:'自我介绍',
                content:'我是一只无忧无虑的鱼'
            }[key]
        })
        dom.innerHTML = str1;
    </script>
    </html>
    
  • negative integer

/^-\d+$/.test('-123')
  • positive integer
/^[+|\d]{1,}/.test('2')
  • integer
/^-?\d+$/.test('-123')
  • Mail
var reg = /^([A-z0-9_-])+\@([A-z0-9_\-\.]+\.([A-z]{2,4}))$/
// var reg = /^[A-z0-9_-]+\@[A-z0-9_\-\.]+\.[A-z]{2,4}$/
var email = '[email protected]'
reg.test(email)
email.match(reg) 
// ['[email protected]', '5', 'qq.com', 'com', index: 0, input: '[email protected]', groups: undefined]
// 子表达式不捕获分组
  • date
/^\d{4}-\d{2}-\d{2}$/.test('1994-12-22')
/^\d{
    
    4}([-\.])\d{
    
    2}\1\d{
    
    2}$/.test('1994-12-22')
/^\d{
    
    4}([-\.])(0[1-9]|1[0-2])\1\d{
    
    2}$/.test('1994-12-22')

Guess you like

Origin blog.csdn.net/uotail/article/details/124718994