JS String篇 字符串常用Api

charAt()

  • 定义
    charAt() 方法从一个字符串中返回指定的字符。

  • 语法

    str.charAt(index)
    
  • 参数

    index
    一个介于0 和字符串长度减1之间的整数。 (0~length-1)
    如果没有提供索引,charAt() 将使用0
  • 描述
    字符串中的字符从左向右索引,第一个字符的索引值为 0,
    最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1。
    如果指定的 index 值超出了该范围,则返回一个空字符串。

  • 示例

    var anyString = "Brave new world";
    
    console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
    console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
    console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
    console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
    console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
    console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
    // The character at index 0 is 'B'
    // The character at index 1 is 'r'
    // The character at index 2 is 'a'
    // The character at index 3 is 'v'
    // The character at index 4 is 'e'
    // The character at index 999 is ''
    

charCodeAt()

  • 定义
    charCodeAt() 方法返回 0 到 65535 之间的整数,表示给定索引处的 UTF-16 代码单元

  • 语法

    str.charCodeAt(index)
    
  • 参数

    index
    一个大于等于 0,小于字符串长度的整数。如果不是一个数值,则默认为 0
  • 返回值

    指定 index 处字符的 UTF-16 代码单元值的一个数字;
    如果 index 超出范围,charCodeAt() 返回 NaN。
    
  • 示例

    "ABC".charCodeAt(0) // returns 65:"A"
    
    "ABC".charCodeAt(1) // returns 66:"B"
    
    "ABC".charCodeAt(2) // returns 67:"C"
    
    "ABC".charCodeAt(3) // returns NaN
    

split()

  • 定义

    split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,
    以一个指定的分割字串来决定每个拆分的位置。 
    
  • 语法

    str.split(separator, limit)
    
  • 参数

    separator
    	指定表示每个拆分应发生的点的字符串。
    	separator 可以是一个字符串或正则表达式。 
    	如果纯文本分隔符包含多个字符,则必须找到整个字符串来表示分割点。
    	如果在str中省略或不出现分隔符,则返回的数组包含一个由整个字符串组成的元素。
    	如果分隔符为空字符串,则将str原字符串中每个字符的数组形式返回。
    limit
    	可选。一个整数,限定返回的分割片段数量。
    	当提供此参数时,split 方法会在指定分隔符的每次出现时分割该字符串,
    	但在限制条目已放入数组时停止。
    	如果在达到指定限制之前达到字符串的末尾,它可能仍然包含少于限制的条目。
    	新数组中不返回剩下的文本。
    
  • 返回值

    返回源字符串以分隔符出现位置分隔而成的一个 Array 
    
  • 示例

    //限制返回个数
    var myString = "Hello World. How are you doing?";
    var splits = myString.split(" ", 3);
    console.log(splits); //["Hello", "World.", "How"]
    var splits1 = myString.split(" ", -3);
    console.log(splits); //["Hello", "World.", "How"]
    
    //靠正则来分割使结果中包含分隔块
    var myString = "Hello 1 word. Sentence number 2.";
    var splits = myString.split(/(\d)/);
    console.log(splits);
    //[ "Hello ", "1", " word. Sentence number ", "2", "." ]
    
    //用split()来颠倒字符串顺序
    const str = 'asdfghjkl';
    const strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
    // split() returns an array on which reverse() and join() can be applied
    
    //移出字符串中分号前的空格 传递一个正则
    var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
    console.log(names);
    var re = /\s*(?:;|$)\s*/;
    var nameList = names.split(re);
    console.log(nameList);
    //Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand 
    //[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
    

substring()

  • 定义

    substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 
    或从开始索引直到字符串的末尾的一个子集。
    
  • 语法

    str.substring(indexStart[, indexEnd])
    
  • 参数

    indexStart
     需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。
    indexEnd
     可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。
    
  • 返回值

    包含给定字符串的指定部分的新字符串。
    
  • 描述

    substring 提取从 indexStart 到 indexEnd(不包括)之间的字符。特别地:
    
    如果 indexStart 等于 indexEnd,substring 返回一个空字符串。
    如果省略 indexEnd,substring 提取字符一直到字符串末尾。
    如果任一参数小于 0 或为 NaN,则被当作 0。
    如果任一参数大于 stringName.length,则被当作 stringName.length。
    如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。
    见下面的例子。
    
  • 示例

    var anyString = "Mozilla";
    // 输出 "Moz"
    console.log(anyString.substring(0,3));
    console.log(anyString.substring(3,0));
    console.log(anyString.substring(3,-3));
    console.log(anyString.substring(3,NaN));
    console.log(anyString.substring(-2,3));
    console.log(anyString.substring(NaN,3));
    
    // 输出 "lla"
    console.log(anyString.substring(4,7));
    console.log(anyString.substring(7,4));
    
    // 输出 ""
    console.log(anyString.substring(4,4));
    
    // 输出 "Mozill"
    console.log(anyString.substring(0,6));
    
    // 输出 "Mozilla"
    console.log(anyString.substring(0,7));
    console.log(anyString.substring(0,10));
    
    //输出 "illa"
    console.log(anyString.substring(anyString.length-4));
    

substr()

  • 警告

    警告: 尽管 String.prototype.substr() 没有严格被废弃 
    (as in "removed from the Web standards"), 
    但它被认作是遗留的函数并且可以的话应该避免使用。它并非JavaScript核心语言的一部分,
    未来将可能会被移除掉。如果可以的话,使用 substring() 替代它.
    
  • 概述

    substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。
    
  • 参数

    start
    	开始提取字符的位置。如果为负值,则被看作 strLength + start,
    	其中 strLength 为字符串的长度(例如,如果 start 为 -3,
    	则被看作 strLength + (-3))。
    length
    	可选。提取的字符数。
    
    
  • 描述

    start 是一个字符的索引。首字符的索引为 0,最后一个字符的索引为 字符串的长度减去1。
    substr 	从 start 位置开始提取字符,提取 length 个字符(或直到字符串的末尾)。
    
    如果 start 为正值,且大于或等于字符串的长度,则 substr 返回一个空字符串。
    
    如果 start 为负值,则 substr 把它作为从字符串末尾开始的一个字符索引。
    如果 start 为负值且 abs(start) 大于字符串的长度,则 substr 使用 0 作为开始提取的索引。
    注意负的 start 参数不被 Microsoft JScript 所支持。
    
    如果 length 为 0 或负值,则 substr 返回一个空字符串。如果忽略 length,
    则 substr 提取字符,直到字符串末尾。
    
  • 示例

    var str = "abcdefghij";
    
    console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
    console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
    console.log("(-3): "     + str.substr(-3));    // (-3): hij
    console.log("(1): "      + str.substr(1));     // (1): bcdefghij
    console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
    console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):
    

slice()

  • 定义

    slice() 方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。
    
  • 语法

    str.slice(beginIndex[, endIndex])
    
  • 参数

    beginIndex
    	从该索引(以 0 为基数)处开始提取原字符串中的字符。如果值为负数,
    	会被当做 strLength + beginIndex 看待,
    	这里的strLength 是字符串的长度(例如, 如果 beginIndex 是 -3 则看作是:strLength - 3)
    endIndex
    	可选。在该索引(以 0 为基数)处结束提取字符串。
    	如果省略该参数,slice() 会一直提取到字符串末尾。
    	如果该参数为负数,则被看作是 strLength + endIndex,
    	这里的 strLength 就是字符串的长度(例如,如果 endIndex 是 -3,则是, strLength - 3)
  • 描述

    slice() 从一个字符串中提取字符串并返回新字符串。
    在一个字符串中的改变不会影响另一个字符串。
    也就是说,slice 不会修改原字符串(只会返回一个包含了原字符串中部分字符的新字符串)。
    
    slice() 提取的新字符串包括beginIndex但不包括 endIndex。下面有两个例子。
    
    例 1:str.slice(1, 4) 提取第二个字符到第四个字符(被提取字符的索引值(index)
    依次为 12,和 3)。
    
    例 2:str.slice(2, -1) 提取第三个字符到倒数第一个字符。
    
  • 示例

    var str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
        str2 = str1.slice(1, 8),
        str3 = str1.slice(4, -2),
        str4 = str1.slice(12),
        str5 = str1.slice(30);
    console.log(str2); // 输出:he morn
    console.log(str3); // 输出:morning is upon u
    console.log(str4); // 输出:is upon us.
    console.log(str5); // 输出:""
    
    var str = 'The morning is upon us.';
    str.slice(-3);     // 返回 'us.'
    str.slice(-3, -1); // 返回 'us'
    str.slice(0, -1);  // 返回 'The morning is upon us'
    

repeat()

  • 定义

    repeat() 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。
    
  • 语法

    str.repeat(count)
    
  • 参数

    count
    	介于 0+Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。
    RangeError: 重复次数不能为负数。
    RangeError: 重复次数必须小于 infinity,且长度不会大于最长的字符串
    
  • 示例

    "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
    
    ({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)   
    //"abcabc",repeat是一个通用方法,也就是它的调用者可以不是一个字符串对象.
    

replace()

  • 定义

    replace() 方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。
    模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。
    如果pattern是字符串,则仅替换第一个匹配项。
    
    原字符串不会改变。
    
  • 语法

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

    regexp (pattern)
    	一个RegExp 对象或者其字面量。该正则所匹配的内容会被第二个参数的返回值替换掉。
    substr (pattern)
    	一个将被 newSubStr 替换的 字符串。其被视为一整个字符串,而不是一个正则表达式。
    	仅第一个匹配项会被替换。
    newSubStr (replacement)
    	用于替换掉第一个参数在原字符串中的匹配部分的字符串。
    	该字符串中可以内插一些特殊的变量名。参考下面的使用字符串作为参数。
    function (replacement)
    	一个用来创建新子字符串的函数,该函数的返回值将替换掉第一个参数匹配到的结果。
    	参考下面的指定一个函数作为参数。
    
  • 示例

    const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
    
    const regex = /dog/gi;
    
    console.log(p.replace(regex, 'ferret'));
    // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
    
    console.log(p.replace('dog', 'monkey'));
    // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
    
    //在 replace() 中使用正则表达式
    //replace() 中使用了正则表达式及忽略大小写标示
    var str = 'Twas the night before Xmas...';
    var newstr = str.replace(/xmas/i, 'Christmas');
    console.log(newstr);  // Twas the night before Christmas...
    
    //交换字符串中的两个单词
    var re = /(\w+)\s(\w+)/;
    var str = "John Smith";
    var newstr = str.replace(re, "$2, $1");
    // Smith, John
    console.log(newstr);
    
    //使 newString 变成 'abc - 12345 - #$*%':
    function replacer(match, p1, p2, p3, offset, string) {
      // p1 is nondigits, p2 digits, and p3 non-alphanumerics
      return [p1, p2, p3].join(' - ');
    }
    var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
    console.log(newString);  // abc - 12345 - #$*%
    

trim() - trimRgiht() - trimLeft

  • 定义

    trim() 方法会从一个字符串的两端删除空白字符。
    	在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 
    	以及所有行终止符字符(如 LF,CR等)。
    trimRight() 删除尾部空格
    trimLeft() 删除头部空格   // 或者叫  trimStart
    
  • 返回值

    一个代表调用字符串两端去掉空白的新字符串。
    
  • 示例

    const greeting = '   Hello world!   ';
    
    console.log(greeting);
    // expected output: "   Hello world!   ";
    
    console.log(greeting.trim());
    // expected output: "Hello world!";
    console.log(greeting.trimRight());
    // expected output: "Hello world!   ";
    console.log(greeting.trimLeft());
    // expected output: "   Hello world!";
    

search()

  • 定义

    search() 方法执行正则表达式和 String 对象之间的一个搜索匹配。
    
  • 语法

    str.search(regexp)
    
  • 参数

    regexp
    	一个正则表达式(regular expression)对象
    	如果传入一个非正则表达式对象 regexp,
    	则会使用 new RegExp(regexp) 隐式地将其转换为正则表达式对象。
    
  • 示例

    var str = "hey JudE";
    var re = /[A-Z]/g;
    var re2 = /[.]/g;
    console.log(str.search(re)); 
    // returns 4, which is the index of the first capital letter "J"
    console.log(str.search(re2)); 
    // returns -1 cannot find '.' dot punctuation
    

indexOf()

  • 定义

    indexOf() 方法返回调用它的 String 对象中第一次出现的指定值的索引,
    	从 fromIndex 处进行搜索。如果未找到该值,则返回 -1
  • 语法

    str.indexOf(searchValue [, fromIndex])
    
  • 参数

    searchValue
    	要被查找的字符串值。
    	如果没有提供确切地提供字符串,searchValue 会被强制设置为 "undefined", 
    	然后在当前字符串中查找这个值。
    	举个例子:'undefined'.indexOf() 将会返回0,因为 undefined 在位置0处被找到,
    	但是 'undefine'.indexOf() 将会返回 -1 ,因为字符串 'undefined' 未被找到。
    fromIndex 可选
    	数字表示开始查找的位置。可以是任意整数,默认值为 0。
    	如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始。
    	(译者注:  fromIndex 的值小于 0,等同于为空情况; fromIndex 的值大于或等于 str.length ,那么结果会直接返回 -1 。)
    	举个例子,'hello world'.indexOf('o', -5) 返回 4 ,因为它是从位置0处开始查找,然后 o 在位置4处被找到。
    	另一方面,'hello world'.indexOf('o', 11) (或 fromIndex 填入任何大于11的值)将会返回 -1 ,
    	因为开始查找的位置11处,已经是这个字符串的结尾了。
    
  • 返回值

    查找的字符串 searchValue 的第一次出现的索引,如果没有找到,则返回 -1
  • searchValue为空时

    //如果 fromIndex 值为空,或者 fromIndex 值小于被查找的字符串的长度,
    //返回值和以下的 fromIndex 值一样:
    'hello world'.indexOf('') // 返回 0
    'hello world'.indexOf('', 0) // 返回 0
    'hello world'.indexOf('', 3) // 返回 3
    'hello world'.indexOf('', 8) // 返回 8
    //如果 fromIndex 值大于等于字符串的长度,将会直接返回字符串的长度(str.length)
    'hello world'.indexOf('', 11) // 返回 11
    'hello world'.indexOf('', 13) // 返回 11
    'hello world'.indexOf('', 22) // 返回 11
    
  • 示例

    //注意 0 并不会被当成 true ,-1 不会被当成 false 。
    //所以当检测某个字符串是否存在于另一个字符串中时,可使用下面的方法:
    'Blue Whale'.indexOf('Blue') !== -1    // true
    'Blue Whale'.indexOf('Bloe') !== -1    // false
    ~('Blue Whale'.indexOf('Bloe'))        // 0, 这是一种错误用法
    
    //使用 indexOf 统计一个字符串中某个字母出现的次数
    var str = 'To be, or not to be, that is the question.';
    var count = 0;
    var pos = str.indexOf('e');
    while (pos !== -1) {
      count++;
      pos = str.indexOf('e', pos + 1);
    }
    console.log(count); // displays 4
    

match()

  • 定义

     match() 方法检索返回一个字符串匹配正则表达式的结果。
    
  • 语法

    str.match(regexp)
    
  • 参数

    regexp
    	一个正则表达式对象。
    	如果传入一个非正则表达式对象,则会隐式地使用 new RegExp(obj)
    	 将其转换为一个 RegExp 。
    	如果你没有给出任何参数并直接使用match() 方法 ,
    	你将会得到一个包含空字符串的 Array :[""]
  • 返回值

    
    如果使用g标志,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组。
    如果未使用g标志,则仅返回第一个完整匹配及其相关的捕获组(Array)。在这种情况下,
    返回的项目将具有如下所述的其他属性。
    	groups: 一个捕获组数组 或 undefined(如果没有定义命名捕获组)。
    	index: 匹配的结果的开始位置
    	input: 搜索的字符串.
    
  • 示例

    const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
    const regex = /[A-Z]/g;
    const found = paragraph.match(regex);
    
    console.log(found);
    // expected output: Array ["T", "I"]
    
    

RegExp.test()

  • 定义

    test() 方法执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 truefalse
  • 语法

    regexObj.test(str)
    
  • 返回值

    如果正则表达式与指定的字符串匹配 ,返回true;否则false
  • 示例

    let str = 'hello world!';
    let result = /^hello/.test(str);
    console.log(result); 
    // true
    // 当设置全局标志的正则使用test()
    var regex = /foo/g;
    
    // regex.lastIndex is at 0
    regex.test('foo'); // true
    
    // regex.lastIndex is now at 3
    regex.test('foo'); // false
    
  • 设置全局标志的正则使用test()

    如果正则表达式设置了全局标志,test() 的执行会改变正则表达式lastIndex属性。
    连续的执行test()方法,后续的执行将会从 lastIndex 处开始匹配字符串,
    (exec() 同样改变正则本身的 lastIndex属性值).
    

转换大小写

1、转换成大写:toUpperCase()
2、转换成小写:toLowerCase()

整理自:MDN

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值