zoukankan      html  css  js  c++  java
  • JS中常用的方法-string

    String

    charAt()

    用于返回指定位置(下标)的字符。

    const str = 'helio guys';
    console.log(str.charAt(3))// i 

    charCodeAt()

    用于返回指定位置的字符的Unicode编码。

    const str = 'helio guys';console.log(str.charCodeAt(3)); //105

    match()

    用于在字符串内检索指定的值或找到一个或多个正则表达式的匹配,返回的是值而不是值的位置。

    const str = 'hello guys';
    console.log(str.match('guys')) // ["guys"]

    // 使用正则匹配字符串
    const strs = '1.hello guys, 2.are you ok?';
    console.log(strs.match(/d+/g)) // ["1", "2"]

    replace()

    替换匹配的字符串。

    const str = 'hello guys';
    console.log(str.replace('guys', 'man')) // hello man

    search()

    用于检索与字符串匹配的子串,返回的是地址,与indexOf()的区别是 search 是强制正则的,而 indexOf只是按字符串匹配的。

    const str = 'hello guys';
    console.log(str.search('guys')) // 6
    console.log(str.indexOf('guys')) // 6

    // 区别

    const string = 'abcdefg.1234';
    console.log(string.search(/./)) // 7(转译之后可以匹配到 . 的位置)
    console.log(string.indexOf(/./)) // -1 (相当于匹配/./,找不到则返回-1,只能匹配字符串)

    split()

    将字符串切割成数组。

    const str = 'hello guys';
    console.log(str.split('')) // ["h", "e", "l", "l", "o", " ", "g", "u", "y", "s"]
    console.log(str.split('', 3)) // ["h", "e", "l"]

    toLocaleLowerCase()& toLowerCase()

    将字符串转换成小写。

    toLocaleUpperCase() & toUpperCase()

    将字符串转换成大写。

    substr()

    用于从起始索引号提取字符串中指定数目的字符。

    const str = 'hello guys';
    console.log(str.substr(2)) // llo guys
    console.log(str.substr(2, 7)) // llo gu

    console.log(str1.substr(-3)) //uys

    substring()

    用于提取字符串中两个指定索引号之间的字符。(与 slice() 和 substr() 方法不同的是,substring() 不接受负的参数。)

    .trim()

    去掉字符串两端的空格。

  • 相关阅读:
    Linux下文件权限的设置
    JavaEE中一些缩写的含义
    Xcode7.1环境下上架iOS App到AppStore 流程 转
    iOS UILabel UITextView自适应文本,或文本大小自适应
    Xcode常用快捷键总结
    iOS9的新特性以及适配方案-----转载
    Python下读取转换unicode的json格式
    python pip 不能用报错: ImportError: No module named _internal
    Python获取二维数组的行列数
    Python作用域
  • 原文地址:https://www.cnblogs.com/maoyizhimi/p/12611312.html
Copyright © 2011-2022 走看看