一、js去除字元串最後一個字元
在js中,我們可以使用字元串的slice()方法或substring()方法來去除最後一個字元。
let str = "hello world!"; str = str.slice(0, -1); console.log(str); //"hello world"
或者使用substring()方法:
let str = "hello world!"; str = str.substring(0, str.length - 1); console.log(str); //"hello world"
這兩種方法的本質相同,都是從字元串的開頭截取到倒數第二個字元。
二、js字元串刪除第一個和最後一個
我們可以使用slice()方法去除第一個和最後一個字元,也可以使用正則表達式。
let str = "hello world!"; str = str.slice(1, -1); console.log(str); //"ello worl"
或者使用正則表達式:
let str = "hello world!"; str = str.replace(/^.|.$/g, ''); console.log(str); //"ello worl"
上面的正則表達式中^表示匹配開頭的字元,.表示匹配任意字元,$表示匹配結尾的字元,|表示或。
三、js字元串取最後一個字元
取最後一個字元我們可以使用charAt()方法或者直接使用slice()方法。
let str = "hello world!"; let lastChar = str.charAt(str.length - 1); console.log(lastChar); //"!"
或者使用slice()方法:
let str = "hello world!"; let lastChar = str.slice(-1); console.log(lastChar); //"!"
四、js字元串去掉最後一個字元
我們已經在之前的內容中介紹了去掉最後一個字元的方法,這裡再重點提一下使用slice()方法的實現。
let str = "hello world!"; str = str.slice(0, -1); console.log(str); //"hello world"
五、js去除字元串某個字元
我們可以使用replace()方法去除特定的字元。
let str = "hello,world!"; str = str.replace(",", ""); console.log(str); //"helloworld!"
要去除所有的逗號,可以使用正則表達式:
let str = "hello,world,again!"; str = str.replace(/,/g, ""); console.log(str); //"helloworldagain!"
六、js去除字元串前後的空格
在js中,使用trim()方法可以去除字元串前後的空格。
let str = " hello world! "; str = str.trim(); console.log(str); //"hello world!"
七、js去除字元串中的空格
我們可以使用replace()方法結合正則表達式去除字元串中的空格。
let str = "hel lo wor ld"; str = str.replace(/\s/g, ""); console.log(str); //"helloworld"
正則表達式中的\s表示匹配空格,g表示全局匹配。
八、js去除字元串中重複的字元
我們可以使用正則表達式結合replace()方法去除字元串中的重複字元。
let str = "hello world!"; str = str.replace(/(.)(?=.*\1)/g, ""); console.log(str); //"helo wrd!"
這裡的正則表達式使用了正向預查和(.)捕獲組,具體實現可以查看相關文檔。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/301689.html