1-1增加
var str="hello";
var s="world";
console.log(str.concat(s))//helloworld
1-2查询
//str[i]
//str.slice(startIndex.endIndex);不包含endIndex
//str.substr(index,length)
//str.substring(startIndex.endIndex);不包含endIndex
<script>
//str[i]
//str.slice(startIndex.endIndex);不包含endIndex
//str.substr(index,length)
//str.substring(startIndex.endIndex);不包含endIndex
var str="hello"
console.log(str[0]);//h
console.log(str.slice(1,3));//el
console.log(str.substr(0,2));//he
console.log(str.substring(0,3));//hel
</script>
//charAT 获取指定下标的值
<script>
var str="hello";
//输出下标为1的值
console.log(str.charAt(1))//e
</script>
1-3获取值的下标 indexOf()和search()
indexOf()(indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。)
var str="hello";
//输出值的下标
console.log(str.indexOf("h"));//0
search()也可以用来判断某个值是否存在(相匹配的字符串的起始位置)
//search用法同indexOf;
var str="你是谁";
var index=str.search("你");
var s=str.search("ta");
console.log(index); //0
console.log(s);//-1
1-4includes判断字符串中是否有字符
var str="hello";
console.log(str.includes("h"));//true
console.log(str.includes("he"));//true
console.log(str.includes("ha"));//flase
例子
<body>
<input type="text" name="" id="input">
<script>
var input = document.getElementById("input");
var arr = [
{ name: "圈住你,你在哪里", id: 4551 },
{ name: "hello", id: 4551 },
{ name: "怪你,啦啦啦", id: 4551 },
{ name: "hello", id: 4551 }
]
/* 1.enter 回车获取关键字 */
input.onkeydown = function (event) {
if (event.keyCode == 13) {
var value = this.value;
/* 2.使用关键字,对数据查询,得到一个数组 */
if (value!="") {
var res = arr.filter(item => {
return item.name.includes(value);
})
}
/* name的字符超过3位以...结尾 */
arr.map(item => {
if (item.name.length > 3) {
return item.name = item.name.slice(0, 3) + "..."
}
})
console.log(res)
}
}
</script>
</body>
1-5split 将字符串分割成数组
var str="hello";
var arr=str.split("");
console.log(arr);//["h", "e", "l", "l", "o"];
console.log(str.split());//["hello"];
console.log(str.split("e"));//["h", "llo"];
例子
将字符串反向输出
var str="hello";
var arr=str.split("");
var a=arr.reverse();
console.log(a);//["o", "l", "l", "e", "h"]
console.log(a.join(""));//"olleh"
1-6match() 返回匹配的字符,返回一个数组
var str="hello";
var arr=str.match("l");
console.log(arr); //["l"];
1-7replace() 替换
replace(替换对象,替换内容)
var str="hello";
console.log(str.replace("l","#"));//he#lo