JavaScript字符串知识点整理

164 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

JavaScript字符串知识点整理

概念

JavaScript 字符串用于存储和处理文本。

字符串可以是插入到引号中的任何字符。我们可以使用单引号或双引号

 var a="hello world" // hello world
 var b='hello world' // hello world

属性

  • constructor:返回创建字符串属性的函数
  • length:返回字符串的长度
  • prototype:允许您向对象添加属性和方法 我们可以使用索引来获取值,字符串的索引从 0 开始。
 var a = "hello world"
 console.log(a.length) // 11
 console.log(a[1]) // e

方法

  • charAt() :返回指定索引位置的字符

  • charCodeAt() :返回指定索引位置字符的 Unicode 值

  • concat()连接两个或多个字符串,返回连接后的字符串

  • fromCharCode() :将 Unicode 转换为字符串

  • indexOf() :返回字符串中检索指定字符第一次出现的位置

  • lastIndexOf() :返回字符串中检索指定字符最后一次出现的位置

  • localeCompare() :用本地特定的顺序来比较两个字符串

  • match()找到一个或多个正则表达式的匹配

  • replace()替换与正则表达式匹配的子串

  • search()检索与正则表达式相匹配的值

  • slice() :提取字符串的片断,并在新的字符串中返回被提取的部分

    • 用法:包含开始索引,不包含结束索引

      • 第二个参数可以省略不写,此时会截取从开始索引往后的所有元素

      • 索引可以传递一个负值,如果传递一个负值,则从后往前计算

        • -1 倒数第一个
        • -2 倒数第二个
  • split() :把字符串分割为子字符串数组

  • substr() :从起始索引号提取字符串中指定数目的字符

  • substring() :提取字符串中两个指定的索引号之间的字符

  • toLocaleLowerCase() :根据主机的语言环境把字符串转换为小写,只有几种语言(如土耳其语)具有地方特有的大小写映射

  • toLocaleUpperCase() :根据主机的语言环境把字符串转换为大写,只有几种语言(如土耳其语)具有地方特有的大小写映射

  • toLowerCase() :把字符串转换为小写

  • toUpperCase() :把字符串转换为大写

  • toString() :返回字符串对象值

  • trim()移除字符串首尾空白

  • valueOf() :返回某个字符串对象的原始值

 <script>
     var x = "hello World"
     var a = "hello"
     var b = "world"
     var y = x.charAt(1) // e
     var y = x.charCodeAt(2) // 108
     var y = a.concat(b) // helloworld
     var y = x.indexOf('e') // 1
     var y = x.lastIndexOf('l') // 9
     var y = x.match('ll') //['ll', index: 2, input: 'hello World', groups: undefined]
     var y = x.replace('ll', 'hh') // hehho World
     var y = x.search('ll') // 2
     var y = x.slice(2) // llo World
     var y = x.slice(2, 4) // ll
     var y = x.slice(2, -1) // llo Worl
     var y = x.split('o') //['hell', ' W', 'rld']
     var y = x.substr(2) // llo World
     var y = x.substr(2, 4) // llo
     var y = x.substring(2, 4) // ll
     var y = x.toLocaleLowerCase() // hello world
     var y = x.toLocaleUpperCase() // HELLO WORLD
     var y = x.toUpperCase() // HELLO WORLD
     var y = x.toLowerCase() // hello world
     var y = x.toString() // hello World
     var y = x.trim() // hello World,去除两端的空格
     var y = x.valueOf() // hello World,返回某个字符串对象的原始值
     console.log(y)
 </script>

运算

对字符串和数字进行加法运算

数字与字符串相加,返回字符串

 y="5"+5; // 55
 z="Hello"+5; // Hello5
 a1=""+5;   // 5
 b="   "+5;   // 得到的结果是   5 (前面是空格)

字符串与字符串进行加法运算

 <script>
     var a = "hello"
     var b = "world"
     console.log(a + b) // helloworld
 </script>

转义字符

文本写在双/单引号中,如果我们需要使用一些特殊的字符,那么可能会报错,不能正确的输出。

这时候我们就需要使用转义字符,将那些特殊字符转义为可以正确输出的字符。

  • \' :单引号
  • \" :双引号
  • \\:反斜杠
  • \n:换行
  • \r:回车
  • \t:tab(制表符)
  • \b:退格符
  • \f:换页符
 "hello world "xiaoming"."