字符串String
1.字符串声明定义
(1)使用字面量(值类型)创建
返回类型是string
let yoo = "yooo.com";
console.log(typeof yoo);
console.log(yoo);
(2)使用对象方法(引用类型)创建
返回类型是object(使用值类型调用方法,js会在执行时将值类型转为对象)
let alison = new String("alison.com");
console.log(typeof alison);
console.log(alison.toString());
2.字符串转义符号
有些字符有双重含义,当想转变其含义时,在字符前加上转义符号\
(1)引号、斜杠… \"
\\
// 引号 在字符前加\
let yoo = "\"yooo.com\"";
console.log(yoo);
let alison = "alison\\alison";
console.log(alison);
(2)制表符\t
// 制表符\t
let ruby = "ru\t\t\tby"
console.log(ruby);
(3)换行\n
// 换行\n
let andy = "an\ndy";
console.log(andy);
3.字符串连接
(1)使用连接运算符+、+=
let year = '2022';
let site = "yooo";
// 使用连接运算符
console.log(year + "的" + site + "一定会更爱自己");
(2)使用模板字面量``
包裹的字符串中可写入引入变量及表达式,支持换行操作
let year = '2022';
let site = "yooo";
// 使用模板字面量
console.log(`${year}的${site}
会发掘出
新的自我`);
模板字面量的嵌套使用
<body>
<script>
function show() {
return "Yooo"
}
let hd = `${show()}酱油`;
console.log(hd);
// 模板字面量嵌套
let lessons = [
{ title: '媒体查询响应式布局' },
{ title: 'FLEX弹性盒模型' },
{ title: 'GRID栅格系统' }
];
function template() {
return `<ul>${lessons.map((item) =>
`<li>${item.title}</li>`)}
</ul>`;
}
document.body.innerHTML = template();
</script>
</body>
4.字符串标签模板
可以通过标签模板提取出模板字面量中的普通字符串和变量,再交给标签函数处理。
<body>
<script>
let name = 'Yooo';
let nick = '酱油';
console.log(tag`${name}的${nick}`);
function tag(strings, name, nick) {
console.log(name);
console.log(nick);
console.log(strings);
}
</script>
</body>
当变量很多时,标签函数的参数可以更改为**…vars**
<body>
<script>
let name = 'Yooo';
let nick = '酱油';
console.log(tag`${name}的${nick}`);
//当变量很多时
function tag(strings, ...vars) {
console.log(vars);
console.log(strings);
}
</script>
</body>
注意:普通字符串的数量永远>变量数
<body>
<script>
let name = 'Yooo';
let nick = '酱油';
// 字符串的数量永远大于变量
console.log(tag`${name}`);
// 当变量很多时
function tag(strings, ...vars) {
console.log(vars);
console.log(strings);
}
</script>
</body>
例:将百度变为百度超链接
<body>
<script>
let lessons = [
{ title: "百度媒体查询响应式布局", author: "百度一下" },
{ title: "FLEX 弹性盒模型", author: "百度知道" },
{ title: "GRID 栅格系统百度教程", author: "没有百度" }
];
function template() {
return `<ul>${lessons.map((item) =>
tag`<li>作者:${item.author} 标题:${item.title}</li>`)
.join("")}
</ul>`;
}
function tag(strings, ...vars) {
return strings.map((str, key) => {
return (str +
(vars[key] ? vars[key].replace("百度", `<a href="https://www.baidu.com">百度</a>`) : "")
);
}).join("");
}
document.body.innerHTML += template();
</script>
</body>
5.字符串基本函数
(1)字符串长度&转成大小写
length
toUpperCase()
toLowerCase()
<body>
<script>
let name = "Yooo";
// 字符串长度
console.log(name.length);
// 字符串都转成大写
console.log(name.toUpperCase());
// 字符串都转成小写
console.log(name.toLowerCase());
</script>
</body>
(2)字符串去掉前后空格
trim()
<body>
<script>
let dog = " Alison";
console.log(dog.length);
// trim()去掉前后空格
console.log(dog.trim().length);
</script>
</body>
<body>
<input type="text" name="password" />
<script>
let ps = document.querySelector("[name='password']");
ps.addEventListener("keyup", function () {
this.value = this.value.trim();
console.log(this.value.length);
})
</script>
</body>
(3)取字符串第n个字符
charAt()
[]
<body>
<input type="text" name="password" />
<script>
let puppy = 'Ruby';
// 取字符串第n个字符
console.log(puppy.charAt(0));
console.log(puppy[0]);
</script>
</body>
(4)字符串截取操作
slice()
substr()
substring()
let name = "alison";
// slice substr substring
// 截取从n开始之后的字符
console.log(name.slice(1));
console.log(name.substr(1));
console.log(name.substring(1));
// slice substring截取从n开始到m之前的字符
// substr截取从n开始的m个字符
console.log(name.slice(1, 3));
console.log(name.substring(1, 3));
console.log(name.substr(1, 3));
// slice 截取从倒数第n个开始到倒数第m个之前的字符
// substr 截取从倒数第n个开始的m个字符
// substring 负数时按0算
console.log(name.slice(-3, -1));
console.log(name.substr(-3, 2));
console.log(name.substring(-3));
(5)检索字符串
indexOf()
includes()
lastIndexOf()
startsWith()
endsWith()
const name = "oalison";
// 查找o在字符串中的下标
console.log(name.indexOf('o'));
// 从第3个字符开始查找o
console.log(name.indexOf('o', 3));
// 从第5个字符开始查找o 找不到返回-1
console.log(name.indexOf('o', 5));
// 从第2个字符串开始查找是否包含o
console.log(name.includes('o', 2));
// 从右开始查找
console.log(name.lastIndexOf('o'));
// 从第3个字符向前查找
console.log(name.lastIndexOf('o', 3));
// 字符串是否以o开头
console.log(name.startsWith('o'));
// 字符串是否以o结尾
console.log(name.endsWith('o'));
const words = ['html', 'css', 'javascript'];
const string = "前端三件套:html、css、javascript";
const status = words.some((word) => {
return string.includes(word);
})
if (status) {
console.log("找到了关键词");
}
(6)字符串替换
replace()
const name = "Yooo.com";
console.log(name.replace("Yooo", "Alison"));
const words = ["html", "css", "js"];
const string = "前端三件套是html、css和js";
// 先将string传给pre,然后通过reduce循环遍历words数组直到遍历结束
const title = words.reduce((pre, word) => {
return pre.replace(word, `<a href="?w=${word}">${word}</a>`);
}, string);
document.body.innerHTML += title;
(7)字符串重复
repeat()
console.log("*".repeat(3));
function phone(mobile, len = 3) {
return String(mobile).slice(0, len * -1) +
"*".repeat(len);
}
console.log(phone(98765432101, 5));