什么字符串
- 用 '' "" `` 包起来字符内容 就是字符串
例:'1'
// 字符串的length
var str = 'hello 2018'
// 字符个数 包含空格
console.log(str.length)
// 字符串也有索引 根据索引 获取其中的一个字符
console.log(str[0]) // 'h'
- 字符串是只读的 不能修改
str[0] = 'W'
console.log(str)
var arr = [1, 2, 3]
arr[1] = 2000
console.log(arr)
- 字符串中的 加号 拼接字符 不是用来求和的
console.log(1 + '1') // '11'
- 字符中拼接变量
- ES6里面提供了 模板字符串
var title = 'xiaoming'
// ` ${变量/表达式} `
var str = `My name is ${title}`
console.log(str)
- 字符串中的操作方法 都存储在String.prototype
console.log(String.prototype)
字符串操作方法
- char 字符
- charAt(索引值)
- 根据索引查找一个字符
var str = 'abcde'
console.log(str.charAt(1)) // 'b'
- 查找一个不存在的字符
console.log(str.charAt(20)) // ""
console.log(str[20]) // undefined
- charCodeAt(索引值)
- 返回相应位置字符的编码
var str = '1'
console.log(str.charCodeAt(0)) // 49
'李'.charCodeAt(0) // 26446
- 查询编码
http://www.mytju.com/classcode/tools/encode_utf8.asp
- 根据字符编码 返回相应字符
String.fromCharCode()
console.log(String.fromCharCode(26446)) // '李'
- concat()
- 拼接字符
var str1 = 'Java'
var str2 = 'Script'
var str = str1.concat(str2, '5.0')
console.log(str) // JavaScript5.0
console.log(str1 + str2 + '5.0') // JavaScript5.0
console.log(`${str1}${str2}5.0`) // JavaScript5.0
-
indexOf/lastIndexOf
- 查找一个字符 在字符串中的索引位置
-
indexOf 以第一次出现字符为主
var str = 'JavaScript'
console.log(str.indexOf('a')) // 1
- lastIndexOf 以最后一次出现的字符为主
console.log(str.lastIndexOf('a')) // 3
console.log(str.indexOf('w')) // -1
console.log(str.lastIndexOf('w')) // -1
//在字符串中 从索引2这个字符开始查找
indexOf(search[,fromIndex])
console.log(str.indexOf('a', 2)) // 3
- match(regexp)
- 检索字符
// var str = 'hello world! llll'
// ["l", index: 2, input: "hello world!", groups: undefined]
console.log(str.match('l'))
// match 支持正则
// 匹配所有的字符l /l/g
// g全局 global
// console.log(str.match(/l/g)) // ["l", "l", "l"]
var str = 'hello 2019 byebye 2018'
// 利用正则/\d+/g 将字符串中的 所有 多位数 以数组的形式查找出来
// \d代表0-9 一个数字 + 代表出现1到多次
console.log(str.match(/\d+/g)) // ["2019", "2018"]
// 正式课 讲正则的时候 还会再讲
var str = 'hello 张华 hello 张华'
// ["张华", index: 6, input: "hello 张华 hello 张华", groups: undefined]
console.log(str.match('张华'))
// ["张华", "张华"]
console.log(str.match(/张华/g))
- replace()
- 替换 支持正则
var str = 'hello world! hello world! hello world!'
// 默认情况下 只能替换第一个找到的字符
console.log(str.replace('l', 'u')) // "heulo world!"
console.log(str.replace(/l/g, 9)) // he99o wor9d!
console.log(str.replace('world', '珠峰')) // hello 珠峰!
console.log(str.replace(/world/g, '珠峰')) // ello 珠峰! hello 珠峰! hello 珠峰!
- 字符串截取
- slice(x, y) 从索引x处开始,截取索引y处 不包含索引y这一项 支持负数
- substr(x, n) 从索引x处开始,截取n个 将截取到内容组成新字符串返回
- substring(x, y) 从索引x处开始,截取索引y处 不包含索引y这一项 不支持负数
var str = 'helloworld!'
// 从索引1截取到索引3这个位置 不包含索引3这一项
console.log(str.slice(1, 3)) // 'el'
// 从索引2开始截取4个字符
console.log(str.substr(2, 4)) // "llo "
// 从索引1截取到索引5这个位置 不包含索引5这一项
console.log(str.substring(1, 5)) // "ello"
// 只传一个参数 slice(x)/substr(x)/substring(x)
// 从索引x处开始截取到末尾
// slice()/substr()/substring() 没传索引或者只传索引0 相当于克隆
- split(分隔符)
- 根据指定分隔符 将字符串拆分成数组
var str1 = 'hello world'
// 没有指定分隔符的情况下 是将整个字符串 作为数组中的第一项
str1.split() // ["hello world"]
str1.split('') // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
str1.split(' ') // ["hello", "world"]
var str2 = 'a1b2c3d'
// 支持正则 \d 代表就是0-9中的一个数
str2.split(/\d/) // ["a", "b", "c", "d"]
- 数组中的join方法
- 将数组按照指定连接符 转换成字符串
// 'hello world'
var str1 = 'hello world'
var arr = str1.split(' ') // ["hello", "world"]
arr.join(' ') // "hello world"
// 反转字符串 "!dlrow olleh"
var str3 = 'hello world!'
str3.split('').reverse().join('')
- toUpperCase() 将字符串中字母转换为大写
- toLowerCase() 将字符串中字母转换为小写
var str = 'hello world'
console.log(str.toUpperCase()) // "HELLO WORLD"
var str = "HELLO WORLD"
console.log(str.toLowerCase()) // "hello world"
- trim()
- 将字符串中首尾空格去掉
var str = ' zhu feng '
console.log(str.trim()) // "zhufeng"
- includes() ES6新方法
- 判断一个字符串中 是否包含字符 包含true 否则false
var str = 'hello world!'
str.includes('world') // true
str.includes('beijing') // false
var str = 'hello'
// str.split('').reverse().join('')
// "olleh"
str.split('') // ["h", "e", "l", "l", "o"]
str.split('').reverse() // ["o", "l", "l", "e", "h"]
str.split('').reverse().join('') // "olleh"
案例:随机验证码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>随机验证码</title>
<style>
.char-code {
width: 150px;
height: 25px;
line-height: 35px;
font-size: 25px;
text-align: center;
/* border: 1px solid blanchedalmond; */
margin: 20px auto;
cursor: pointer;
user-select: none;
}
</style>
</head>
<body>
<div class="char-code" id="charCode"></div>
<input type="text" id="strText">
<input type="button" value=" 获取验证码" id="btn">
<script>
// var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// str.length 62
// str 索引(0~str.length-1)
// 1.生成四个随机索引 根据索引找到相应字符 拼接起来
// 2. 0 ~ str.length-1 随机整数
// var strCode = '';
// for (var i = 0; i < 4; i++) {
// // 生成一个 0~61的随机索引
// var ind = Math.round(Math.random() * str.length - 1)
// // 根据索引ind 获取相应的字符
// // 将每一次得到的字符拼接起来
// strCode += str[ind];
// }
// console.log(strCode);
// var str = ''
// str += 'a'
// str += 'b'
// str += 'c'
// console.log(str) // "abc"
function createCode(len) {
// 如果传递进来的值 不是数字类型或者是NaN 我们需要设置一个默认值
// if (typeof len !== 'number' || isNaN(len)) {
// len = 4;
// }
var len = len || 4;
var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var strCode = '';
for (var i = 0; i < len;) {
// 生成一个 0~61的随机索引
var ind = Math.round(Math.random() * (str.length - 1));
// 根据索引ind 获取相应的字符
var char = str[ind];
// 如果strCode不存在这个字符 再进行拼接
if (!strCode.includes(char)) {
// 进行字符拼接
// 将每一次得到的字符拼接起来
strCode += char;
i++; //拼接一次就累加一次
}
}
return strCode;
}
// console.log(createCode())
var btn = document.getElementById('btn');
var charCode = document.getElementById('charCode');
var strText = document.getElementById('strText');
btn.onclick = function () {
// console.log(strText.value);
charCode.innerHTML = createCode(strText.value);
}