最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JS替換字符串中指定位置的字符(多種方法)

 更新時間:2020年05月28日 08:38:38   作者:秦老爺子  
這篇文章主要介紹了js替換字符串中指定位置的字符,本文通過兩種方法實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

假設(shè)有一個字符串,可能'Good Morning'也可能是'Hello World',我想將第五個字符,替換成'-'。
因?yàn)樽址m然可以像數(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方法,用于提取字符串中介于兩個指定下標(biāo)之間的字符,也就是說可以用'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為全局標(biāo)志)。

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:字符串表達(dá)式包含要替代的子字符串。
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> 

總結(jié)

到此這篇關(guān)于JS替換字符串中指定位置的字符的文章就介紹到這了,更多相關(guān)js替換字符內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

宜川县| 理塘县| 东海县| 开封县| 西乡县| 宁蒗| 龙山县| 蛟河市| 苏尼特左旗| 钟祥市| 措勤县| 商丘市| 崇明县| 和政县| 阳城县| 房产| 大英县| 平舆县| 鹿泉市| 疏勒县| 姜堰市| 阳东县| 柳江县| 云南省| 石城县| 永善县| 华宁县| 德惠市| 亳州市| 泽州县| 邢台县| 白河县| 共和县| 海淀区| 台北县| 麻城市| 拜城县| 凤凰县| 来宾市| 静乐县| 休宁县|