javaScript操作字符串的方法

154 阅读10分钟

前言

这是我写的第一篇文章,我只是一个刚刚工作没多久的小白,想记录自己的成长,多多指教~

最近在刷leetCode,感觉对js基础还不够熟练,所以。。。总结了一下使用js对字符串的一些操作方法

正文

首先通过下面的截图我们能够看到String的原型上有这么多方法,接下来按照图片中的顺序一一尝试。

  1. String的属性length: 用于表示某个字符串的长度

    在控制台输入以下代码:

    'aa'.length   // 2
    
  2. String对象的方法anchor: 用于创建 HTML 锚

    在实际项目中,目前还没有使用过该方法,于是自己查阅了一下,供参考:

    • 首先创建一个.html文件,在浏览器中打开查看Elements
    • 接下来在该文件中写入一下代码并在浏览器中打开查看Elements
    <script type="text/javascript">
        var txt = "Hello world!"
        document.write(txt.anchor("myanchor"))
    </script>
    

    • 在图片中看到生成了一个a标签,并添加了name属性,例子中的myanchor为锚定义名称。
  3. String对象的方法big用于把字符串显示为大号字体

    • 方法同上(此处简略说明):
  4. String对象的方法blink, blod, small, fixed, fontcolor, fontsize, italics, link, strike(已废弃), sub(已废弃), sup(已废弃)

    • 此处不在赘述(上图😊):
  5. String对象的方法charAt返回在指定位置的字符

    'ab'.charAt(0)   // "a"
    'ab'.charAt(1)   // "b"
    
  6. String对象的方法charCodeAt返回在指定的位置的字符的 Unicode 编码

    'aA'.charCodeAt(0)  // 97
    'aA'.charCodeAt(1)  // 65
    
  7. String对象的方法codePointAt指定位置的字符的 Unicode 编码

    • 方法同上

    • charCodeAt的区别:

      • charCodeAt: 返回值是 0 - 65535 之间的整数。如果 index 是负数,或大于等于字符串的长度,则返回 NaNcodePointAt:如果 index 是负数,或大于等于字符串的长度,则 codePointAt() 返回 undefined
       'aA'.charCodeAt(-1)  // NaN
       'aA'.codePointAt(-1)  // undefined
      
      • 更详细的区别有待查阅😊
  8. String对象的方法concat用于连接两个或多个字符串

    'a'.concat('b')  // "ab"
    'a'.concat('b', 'c')  // "abc"
    
  9. String对象的方法endsWith用于确定字符串是否以指定字符串的字符结尾

    'ab'.endsWith('b')  // true
    'ab'.endsWith('a')  // false
    
  10. String对象的方法includes用于确定字符串是否包含指定字符串的字符

    'ab'.includes('b')  // true
    'ab'.includes('c')  // false
    'AA'.includes('A')  // true
    'AA'.includes('a')  // false
    
  11. String对象的方法indexOf用于返回某个指定的字符串值在字符串中首次出现的位置

    'aa'.indexOf('a')  // 0
    'ab'.indexOf('b')  // 1
    
  12. String对象的方法lastIndexOf用于返回一个指定的字符串值最后出现的位置

    'aba'.lastIndexOf('a')  // 2
    'adrerers'.lastIndexOf('s') // 7
    
  13. String对象的方法localeCompare用本地特定的顺序来比较两个字符串

    'a'.localeCompare('b')  // -1
    'b'.localeCompare('a')  // 1
    'a'.localeCompare('a')  // 0
    
  14. String对象的方法match可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配

    'ab'.match('a')  // ["a", index: 0, input: "ab", groups: undefined]
    'ab'.match('c')  // null
    'a122b44'.match(/\d+/g)  //  ["122", "44"]
    
    说明:用于匹配字符串时与`indexOf``lastIndexOf`相类似,区别在于返回值不同。
         该方法返回值为数组。
    
  15. String对象的方法matchAll用于返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器

    const regexp = /\d+/g;
    const strh = 'test12';
    const array = [...strh.matchAll(regexp)];
    console.log(array);
     // [Array(1)]
     // 	     0: ["12", index: 4, input: "test12", groups: undefined]
     //	length: 1
     //  __proto__: Array(0)
     
     说明:该方法接受的参数要求为正则表达式,如果参数不是正则,则会转换为正则表达式进行匹配
    
  16. String对象的方法normalize按照指定的一种 Unicode 正规形式将当前字符串正规化

    let string1 = '\u00F1';           // ñ
    let string2 = '\u006E\u0303';     // ñ
    
    string1 = string1.normalize('NFD');
    string2 = string2.normalize('NFD');
    
    console.log(string1 === string2); // true
    console.log(string1.length);      // 2
    console.log(string2.length);      // 2
    
    说明: 参数"NFC""NFD""NFKC",或 "NFKD" 其中的一个, 默认值为 "NFC"
  17. String对象的方法padEnd用于使用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充

    'abc'.padEnd(10);          // "abc       "
    'abc'.padEnd(10, "foo");   // "abcfoofoof"
    'abc'.padEnd(6, "123456"); // "abc123"
    'abc'.padEnd(1);           // "abc"
    
  18. String对象的方法padStart用于使用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充

    'abc'.padStart(10);         // "       abc"
    'abc'.padStart(10, "foo");  // "foofoofabc"
    'abc'.padStart(6,"123465"); // "123abc"
    'abc'.padStart(1); 
    
  19. String对象的方法repeat构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。

    "abc".repeat(-1)     // RangeError: repeat count must be positive and less than inifinity
    "abc".repeat(0)      // ""
    "abc".repeat(1)      // "abc"
    "abc".repeat(2)      // "abcabc"
    "abc".repeat(3.5)    // "abcabcabc" 参数count将会被自动转换成整数.
    "abc".repeat(1/0)    // RangeError: repeat count must be positive and less than inifinity
    
  20. String对象的方法replace返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项。

    const p = 'dog aa dog  bb dog';
    const regex = /dog/gi;
    console.log(p.replace(regex, 'ferret'));  // ferret aa ferret  bb ferret
    console.log(p.replace('dog', 'monkey'));  // monkey aa dog  bb dog
    
  21. String对象的方法search用于执行正则表达式和 String 对象之间的一个搜索匹配,匹配成功则返回首次匹配项的索引,否则返回-1

    const str = 'The4ds545';
    const regex = /\d/g;
    str.search(regex);	// 3
    
    const str2 = 'Theds';
    const regex = /\d/g;
    str2.search(regex);	 // -1	
    
  22. String对象的方法slice用于提取某字符串的一部分,返回新的字符串,不改变原字符串

    // 一个参数 && 正数: 从该位置开始截取到最后
    'abcdefg'.slice(1);	 // 'bcdefg'
    // 一个参数 && 负数: 从字符串的末尾方向查找该位置,再截取到最后
    'abcdefg'.slice(-1); // g
    // 两个参数: 从参数一截取到参数二
    'abcdefg'.slice(1,2);	// 'b'
    'abcdefg'.slice(1,-2);  // 'bcde'
    'abcdefg'.slice(-1,-2); // ''
    'abcdefg'.slice(-3,-2); // 'e'
    
  23. String对象的方法split用于使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置

    'a b c d'.split(' ')   // ['a', 'b', 'c', 'd']
    'a,b,c,d'.split(',')   // ['a', 'b', 'c', 'd']
    
  24. String对象的方法startsWith用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false

    'abcd'.startsWith('a')  // true
    
  25. String对象的方法replaceAll: 与20相同,可理解为全部替换

    const p = 'dog aa dog  bb dog';
    const regex = /dog/gi;
    console.log(p.replaceAll(regex, 'ferret'));  // ferret aa ferret  bb ferret
    console.log(p.replaceAll('dog', 'monkey'));  // monkey aa monkey  bb monkey
    
  26. String对象的方法substr返回一个字符串中从指定位置开始到指定字符数的字符

    // 参数:1. 开始位置  2. 截取长度(可省略)
    'abcd'.substr(1)   // 'bcd'
    'abcd'.substr(1, 2)  // 'bc' 
    'abcd'.substr(-1)   // 'd'
    'abcd'.substr(-2, 2)   // 'cd'
    
    说明:尽管 String.prototype.substr(…) 没有严格被废弃 (as in "removed from the Web 
         standards"), 但它被认作是遗留的函数并且可以的话应该避免使用。它并非JavaScript核心
         语言的一部分,未来将可能会被移除掉。如果可以的话,使用 substring() 替代它.
    
  27. String对象的方法substring返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集

    // 参数:1. indexStart  2. indexEnd
    // 如果 indexStart 等于 indexEnd,substring 返回一个空字符串。
    'abcd'.substring(1,1)  // ''
    // 如果省略 indexEnd,substring 提取字符一直到字符串末尾
    'abcd'.substring(1)  // 'bcd'
    // 如果任一参数小于 0 或为 NaN,则被当作 0
    'abcd'.substring(-1)  // 'abcd'
    'abcd'.substring(NaN)  // 'abcd'
    // 如果任一参数大于 stringName.length,则被当作 stringName.length
    'abcd'.substring(17)  // 'bcd'
    // 如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样
    'abcd'.substring(31)  // 'bc'
    
    ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
    'abcd'.substring(3, -1)  // 'abcd'
    首先:-1 => 0  然后 4 > 0 于是 'abcd'.substring(4,-1)  => 'abcd'.substring(0, 4) 
    
    
  28. String对象的方法toLocaleLowerCase用于根据任何指定区域语言环境设置的大小写映射,返回调用字符串被转换为小写的格式

    // 参数:指明要转换成小写格式的特定语言区域, 如果参数是以数组形式出现则默认是主机环境的当前区域(locale)设置
    'ALPHABET'.toLocaleLowerCase(); // 'alphabet'
    
    '\u0130'.toLocaleLowerCase('tr') === 'i';    // true
    '\u0130'.toLocaleLowerCase('en-US') === 'i'; // false
    
    let locales = ['tr', 'TR', 'tr-TR', 'tr-u-co-search', 'tr-x-turkish'];
    '\u0130'.toLocaleLowerCase(locales) === 'i'; // true
    
  29. String对象的方法toLocaleUpperCase根据本地主机语言环境把字符串转换为大写格式,并返回转换后的字符串

    'istanbul'.toLocaleUpperCase('en-US')   // "ISTANBUL"
    'istanbul'.toLocaleUpperCase('TR')   	// "İSTANBUL"
    
  30. String对象的方法toLowerCase会将调用该方法的字符串值转为小写形式,并返回

    'A'.toLowerCase()  // 'a'
    '中文简体 zh-CN || zh-Hans'.toLowerCase()  // '中文简体 zh-cn || zh-hans'
    
  31. String对象的方法toUpperCase会将调用该方法的字符串值转为大写形式,并返回

    'a'.toLowerCase()  // 'A'
    
  32. String对象的方法trim会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)

    '    a   b  '.trim()   // "a   b"
    
  33. String对象的方法trimEnd从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名

    '    a    '.trimEnd()   // '    a' 
    
  34. String对象的方法trimLeft同37

  35. String对象的方法trimRight同34

  36. String对象的方法trimStart方法从字符串的开头删除空格。trimLeft() 是此方法的别名

    '   a   '.trimStart()   // 'a   '
    
  37. String对象的方法valueOf返回 String 对象的原始值

    'aaa'.valueOf()   // 'aaa'
    
  38. String对象的方法Symbol(Symbol.iterator)返回一个新的Iterator对象,它遍历字符串的代码点,返回每一个代码点的字符串值

    const str = 'The quick red fox jumped over the lazy dog\'s back.';
    const iterator = str[Symbol.iterator]();
    let theChar = iterator.next();
    
    while (!theChar.done && theChar.value !== ' ') {
      console.log(theChar.value, 'theChar', theChar);
      theChar = iterator.next()
    }
    
    //  "T" "theChar" Object { value: "T", done: false }
    //  "h" "theChar" Object { value: "h", done: false }
    //  "e" "theChar" Object { value: "e", done: false }
    
    说明:遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。
         任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。
         Iterator 的作用有三个:
            - 为各种数据结构,提供一个统一的、简便的访问接口;
            - 使得数据结构的成员能够按某种次序排列;
            - ES6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费。
    

最后

biu biu biu ~ ❤️❤️❤️❤️ 点关注 🙈🙈 不迷路