JS替換字符串中指定位置的字符(多種方法)
假設有一個字符串,可能'Good Morning'也可能是'Hello World',我想將第五個字符,替換成'-'。
因為字符串雖然可以像數(shù)組那樣獲取某一位置字符'Hello World'[4],但是不能像數(shù)組那樣直接修改某一位置的字符'Hello World'[4] = '-',這樣是行不通的,但是可以把它切分成數(shù)組,修改某一位置的值,然后在合并回來。
方法1:
const replaceStr1 = (str, index, char) => {
const strAry = str.split('');
strAry[index] = char;
return strAry.join('');
}
replaceStr(str1, 4, '-'); // => Good-Morning
replaceStr(str2, 4, '-'); // => Hell- World
js的字符串有個substring方法,用于提取字符串中介于兩個指定下標之間的字符,也就是說可以用'Hello World'.substring(0, 4),得到Hell,加上要替換的字符,再加上后面的字符串就可以。
方法2:
const replaceStr2 = (str, index, char) => {
return str.substring(0, index) + char + str.substring(index + 1);
}
replaceStr2(str1, 4, '-'); // => Good-Morning
replaceStr2(str2, 4, '-'); // => Hell- World
ps:下面看下js替換字符串中所有指定的字符
第一次發(fā)現(xiàn)JavaScript中replace()方法如果直接用str.replace("-","!")只會替換第一個匹配的字符.
而str.replace(/\-/g,"!")則可以全部替換掉匹配的字符(g為全局標志)。
replace()
Thereplace()methodreturnsthestringthatresultswhenyoureplacetextmatchingitsfirstargument
(aregularexpression)withthetextofthesecondargument(astring).
Iftheg(global)flagisnotsetintheregularexpressiondeclaration,thismethodreplacesonlythefirst
occurrenceofthepattern.Forexample,vars="Hello.Regexpsarefun.";s=s.replace(/\./,"!");//replacefirstperiodwithanexclamationpointalert(s);
producesthestring“Hello!Regexpsarefun.”Includingthegflagwillcausetheinterpreterto
performaglobalreplace,findingandreplacingeverymatchingsubstring.Forexample,vars="Hello.Regexpsarefun.";s=s.replace(/\./g,"!");//replaceallperiodswithexclamationpointsalert(s);
yieldsthisresult:“Hello!Regexpsarefun!”
所以可以用以下幾種方式.:
string.replace(/reallyDo/g,replaceWith); string.replace(newRegExp(reallyDo,'g'),replaceWith);
string:字符串表達式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替換的子字符串。
Js代碼
<script type="text/javascript">
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);
} else {
return this.replace(reallyDo, replaceWith);
}
}
</script>
總結
到此這篇關于JS替換字符串中指定位置的字符的文章就介紹到這了,更多相關js替換字符內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript之querySelector和querySelectorAll使用說明
其實關于querySelector和querySelectorAll的介紹說明很多,在此主要是做個記錄2011-10-10
體驗js中splice()的強大(插入、刪除或替換數(shù)組的元素)
javascript splice()算是最強大的了,它可以用于插入、刪除或替換數(shù)組的元素。下面來一一介紹,感興趣的朋友2013-01-01
jQuery及JS實現(xiàn)循環(huán)中暫停的方法
這篇文章主要介紹了jQuery及JS實現(xiàn)循環(huán)中暫停的方法,以實例形式分析了循環(huán)中暫停的原理及實現(xiàn)技巧,非常具有實用價值,需要的朋友可以參考下2015-02-02
js動態(tài)創(chuàng)建表格,刪除行列的小例子
這篇文章介紹了js動態(tài)創(chuàng)建表格,刪除行列的實例代碼,有需要的朋友可以參考一下2013-07-07
JavaScript算法題之如何將一個數(shù)組旋轉k步
這篇文章主要給大家介紹了關于JavaScript算法題之如何將一個數(shù)組旋轉k步的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-03-03
javascript結合Cookies實現(xiàn)瀏覽記錄歷史
最近在工作當中遇到一個問題 有個頁面需要添加一個瀏覽歷史記錄功能,具體來說就是要記錄下用戶在此網站的點擊歷史 并把它們降序排列出來(只顯示前6個瀏覽歷史而且不能重復)。2008-09-09

