字符串

120 阅读3分钟

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

创建字符串

两种方式创建的字符串除了在控制台打印显示区别外,没有其他区别。

字面量:
var str = 'hello'
构造函数创建
var str = new string('hello')

字符串操作

字符串有length属性 -> 表示字符串长度,也就是字符串中字符串个数

注:空字符也算一个字符

字符串是按照索引排列,可以通过索引访问每一个字符字符值只能访问不能改变

var str = 'hello world'
console.log(str[1])
str[1] = 'z'
console.log(str[1])

for循环遍历字符串

包装数据类型

  1. 字符串、数值、布尔值是一个包装数据类型
  2. 当使用时会自动转换成复杂数据类型,使用完自动转回基本数据类型
  3. 使用点语句.toString()

字符串常用的方法

chaeAt

charAt(索引)是找到字符串中指定索引位置的内容返回

var str = "Jack"
//使用charAt 找到字符串中的某一个内容
var index = str.charAt(2)
console.1og(index) // C

如果没有对应的索引,那么就会返回空字符串

var str = Jack"
//使用charAt 找到字符串中的某一个内容
var index = str.charAt(10)
console.1og(index) // ''

indexOf

indexOf就是按照字符找到对应的索引

var str.'Jack'
//使用indexOf 找到对应的索引
var index = str.indexOf('J')
console. log(index) //0

substring

substring是用来截取字符串使用的

语法:substring(从哪个索引开始, 到哪个索引截止),包含开始索引,不包含结束索引

var str = 'hello'
//         01234
//使用substring 截取字符串
var newStr = str.substring(1, 3)
console.log(newStr) // el

substr

substr也是用来截取字符串的

语法: substr(从哪个索引开始,截取多少个)

var str = 'hello'
//         01234
//使用substr 截取字符串
var newstr = str.substr(1, 3)
console.log(newstr) // ell

replace

用于在字符串中用一些字符替换另一些字符

var str= "Visit Microsoft!"
document.write(str.replace('Microsoft', "school"))
输出=> Visit school!

split

分割字符串,将分割之后的字符存入数组返回

var str = 'javacrit-htm-ss'
var arr = str.split(-)
arr => [javascripthtml,css]

//字符串转数组:var arr = str.split('')

concat

连接两个字符串,返回连接之后的字符串

var str = 'hello'
vars1 = str.concat('world')
s1 => helloworld

trim

trim()
=>方法删除字符串两端的空白符
=>返回去掉空格的新字符

startsWith()&endsWith()

startsWith(子字符串)
    =>判断字符串是否以子字符串开始
    =>返回true| false
    
endsWith(子字符串)
    =>判断字符串是否以子字符串结束
    =>返回true| false 

toLowerCase和toUpperCase

这两个方法分别使用用来给字符串转成小写母和大写字母的

var str = hello
//使用toUpperCase 转换成大写
var upper = str.toUpperCase()
console.log(upper) // HELLO

//使用tolowerCase 转换成小写
var lower = upper.toLowercase()
console.log(lower) // hello

模板字符串

  1. 模板字符串

    var str = 'hello' 
    var str = "hello" 
    var str = `hello` //模板字符串 
    模板语法 `${变量}` 
             ${简单运算} 
    
  2. 作用

  • 字符串拼接

    var a = 10 
    var b = 20 
    var c = `${a}+${b}=${a+b}` 
    console.log(c)
    
  • 换行不用连接符

    var title = '模板字符串' 
    var str = `<div> 
        <h2>${title}</h2> 
        <p>1.作用</p> 
        <p>拼接字符串,换行不用连接符</p> 
    </div>` 
    document.write(str)
    

严格模式

不严格的体现:

  • 声明变量可以不使用var关键字

  • 形参重复

    <script>
        'use strict'
        //下面代码书写就要按照严格模式书写
    </script>
    

ASCII码

  1. ASCII

image.png

  1. GBK

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

  1. Unicode

unicode编码,也叫(万国码,统-码),unicode对照表就是一个和ASCII一样的对照表,只不过变得很大很大,因为存储的内容特别的多,而且包含了世界.上大部分国家的文字,所以我们的文字和字符现在在存储的时候,都是按照unicode编码转换成数字进行存储,UTF-8就是一种8位的unicode字符集

  1. charCodeAt方法

charCodeAt(索引)就是返回对应索引位置的unicode编码

var str = "Jack"

//使用charAt 找到字符串中的某一 个内容
var index = str.charCodeAt(0)

console.log(index) // 74

一个英文字符占用一个字节,一个中文字符占用两个字节。中文字符unicode编码大于255