javascript去除特定字符的方法是:1、使用replace函數(shù)替換,語(yǔ)法“元素.replace('需要去除的字符串', '')”;2、使用字符串分割函數(shù)再聚合。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
本文實(shí)例講述了JS實(shí)現(xiàn)字符串中去除指定子字符串方法。分享給大家供大家參考,具體如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> /*方法一:使用replace函數(shù)替換*/ //去除字符串中含有的某字符串:str = str.replace('give', ''); var str = 'Could you please give me a simple example of how to'; console.log("str=======前==" + str);//str=======前==Could you please give me a simple example of how to //注意:此處不可寫作:str.replace('give', '');要寫作:str = str.replace('give', ''); // replace:返回新的字符串,一定要重新接收,不然替換不了 str = str.replace('give', '');//去掉字符的位置不定,可能在字符串中間,也可能在末尾 console.log("str.replace('give', '')==" + str.replace('give', '')); //str.replace('give', '')==Could you please me a simple example of how to console.log("str=======后==" + str);//str=======后==Could you please me a simple example of how to /*方法二:使用字符串分割函數(shù)再聚合*/ var str = "hello world!"; var items = str.split("o"); //會(huì)得到一個(gè)數(shù)組,數(shù)組中包括利用o分割后的多個(gè)字符串(不包括o) var newStr = items.join("");//數(shù)組轉(zhuǎn)成字符串,元素是通過(guò)指定的分隔符進(jìn)行分隔的。此時(shí)以空串分割:即直接連接 console.log("newStr=====" + newStr);// newStr=====hell wrld! //會(huì)得到一個(gè)新字符串,將數(shù)組中的數(shù)組使用空串連接成一個(gè)新字符串 </script> </body> </html>
運(yùn)行結(jié)果:
【推薦學(xué)習(xí):javascript高級(jí)教程】