字符串

50 阅读2分钟

创建字符串

与创建对象和数组方式一样,字符串也可通过以下方式创建

  1. 字面量方式创建 var str='helloworld'
  2. 构造函数创建 var str1=new String('helloworld')

与数组下标类似,字符串是由一系列字符构成,每个字符都对应自己的下标,从0开始

字符串遍历

for(var i=0,i<str.length;i++){console.log(str)}

当使用点语句调用字符串属性和方法时,自动转为复杂数据类型,使用完又转为基本数据类型,JS里此种类型为包装类型.

基本数据类型复杂数据类型
stringString
numberNumber
booleanBoolean

常用方法

  1. charAt :根据下标返回字符

     var str = 'helloworld'
     var newStr = str.charAt(5)
     console.log(newStr)
    
  2. indexOf :返回字符在字符串的下标,如果字符不存在,返回值为-1

     var newStr = str.indexOf('w')
     console.log(newStr)
    
  3. lastIndexOf:作用于indexOf一样,区别为检索字符时是从右往左找,下标仍为真实下标

     var newStr=str.lastIndexOf('l')
     console.log(newStr)
    
  4. substring: 截取字符串 substring(从哪个索引开始,到哪个索引结束)

     var newStr=str.substring(0,4)
     console.log(newStr)
    
  5. substr: 截取字符串 substr(从哪个索引开始,截取几个)

    var newStr=str.substr(0,5) console.log(newStr)

  6. replace: 用一些字符替换另一些字符 replace('被替换的字符','新字符')

    var str="Visit Microsoft!"
    document.write(str.replace('Microsoft', "school"))
    输出 => Visit school!
    
  7. split: 分割字符串,将分割后的字符存入数组返回

    var str = 'javascript-html-css'
    var arr = str.split('-')
    arr =>  [javascript,html,css]
    
  8. concat: 连接两个字符串,返回连接之后的字符串

    var str = 'hello'
    var s1 = str.concat('world')
    s1 => helloworld
    
  9. trim : 删除字符串两端的空白符,返回值为去掉空格的新字符

     var str='          huzhixiong       '
     console.log(str)
     var newStr=str.trim()
     console.log(newStr)  //huzhixiong
    
  10. startsWith(子字符串) : 判断字符串是否以子字符串开头,若是,返回值为true

     var str = 'https://juejin.cn/editor/drafts/7134952237138673677'
     var isOk = str.startsWith('https')
     console.log(isOk)
     var isOk=str.endsWith('3677')
     console.log(isOk)
    
  11. endsWith(子字符串) : 判断字符串是否以字符串结束,若是,返回为true

  12. toLowerCase : 字符串转换成小写

    var str =hello
    var upper= str.toUpperCase()
    console.log(upper)//HELLO
    
  13. toUpperCase :字符串转换为大写

模板字符串

var str = 'hello' 
var str = "hello" 
var str = `hello` 

模板字符串 模板语法 ${变量} ${简单运算} 2. 作用 2.1字符串拼接 2.2换行不用连接符

function(test3){
var a=10
var b=20
var c= `${a}+${b}=${a+b}`
 conlog.log(c)
  }

1.2 换行显示字符串时,

严格模式 js相对来说是一门不严谨的语言 不严格体现在:1.变量不声明也能使用 2.函数形参可以重复(不会报错只是覆盖) 开启严格模式: 'use strict'

计算机编码

ASLL :- 我们可以简单的理解为, a ~ z / A ~ Z / $ / @ /… 之类的内容都有一个自己的编号,然后在计算机存储的时候,是存储的这些编号,我们看的时候,也是通过这些编号在解析成我们要看到的内容给我们看到.需要注意的是

GBK :汉字内码扩展规范,共收录了21003个汉字

unicode:也叫万国码,包含了世界上大部分国家的文字,我们的 UTF-8 就是一种 8 位的unicode字符集,

charCodeAt方法: 中文字符unicode编码大于255