JS 字符串詳解

增加

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( ) 以...開(kāi)頭的字符串
// startsWith() 以...開(kāi)頭的字符串
// 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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容