增加
concat 拼接
var a = 'hello'
var b = "world"
console.log(a.concat(b)); // helloworld
查詢
- slice(startIndex,endIndex)
第二個(gè)參數(shù) 為長(zhǎng)度
var arr = "hello"
console.log(arr.slice(0)); // hello
console.log(arr.slice(0,3)); // hel
- substr(index,length)
第二個(gè)參數(shù) 為長(zhǎng)度
console.log(arr.substr(0,3)); // hel
console.log(arr.substring(0,2)); // he
- charAt(index) 根據(jù)下標(biāo)查找對(duì)應(yīng)的值
var str = "hello"
console.log(str.charAt(1)); // e
- indexOf(value) 根據(jù)值查找對(duì)應(yīng)的下標(biāo) 找不到返回-1
var arr = "hello";
console.log(arr.indexOf('e')); // 1
- lastIndexOf(value) 從后面根據(jù)值查找對(duì)應(yīng)的下標(biāo) 找不到返回-1
var str = "a?f?e"
const index = str.lastIndexOf("?")
console.log(index) // 3
console.log(str.substr(0, index)) // a?f
console.log(str.substr(index + 1)) // e
- search(value) 根據(jù)值查找對(duì)應(yīng)的下標(biāo) 找不到返回-1
var str = "你是誰(shuí)"
var index = str.search("她")
console.log(index); // -1
- includes 是否包含某位(多位)字符 返回boolean
var arr = "hello"
console.log(arr.includes("eh")); //false
- match(value) 返回匹配的字符串,返回的是數(shù)組
var str ="hello"
var arr = str.match("l")
console.log(arr); // ["l", index: 2, input: "hello", groups: undefined]
// 找不到返回 null
length 字符串的長(zhǎng)度
var str = "hello"
console.log(str.length); // 5
其他方法
- split( ) 將字符串分割成字符串?dāng)?shù)組
var str = "hello"
console.log(str.split()); // 將字符串轉(zhuǎn)為數(shù)組 ["hello"]
console.log(str.split("")); // ["h","e","l","l","o"]
console.log(str.split("e"));// ["h","llo"]
- replace( ) 替換字符串
var str = "hello"
console.log(str.replace("l","*")); // he*lo
- trim( ) 去除字符串前后的空格
var str = " hello ";
var arr = []
arr.push(str.trim())
console.log(arr) // ["hello"]
- startsWith( ) 以...開頭的字符串
// startsWith() 以...開頭的字符串
// endsWith() 以...結(jié)束的字符串
var str = "武漢"
console.log(str.startsWith("武")) // true
console.log(str.endsWith("漢")) // true
字符串模板
var str = 10;
var b = "hello";
console.log(str+b); // 10hello
var sum = `${str}hello`;
console.log(sum); // 10hello