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

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

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

假設(shè)有一個(gè)字符串,可能'Good Morning'也可能是'Hello World',我想將第五個(gè)字符,替換成'-'。
因?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的字符串有個(gè)substring方法,用于提取字符串中介于兩個(gè)指定下標(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("-","!")只會(huì)替換第一個(gè)匹配的字符.
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

象山县| 拉孜县| 长顺县| 潞西市| 大竹县| 南江县| 平利县| 胶州市| 西畴县| 临西县| 福州市| 南雄市| 贵定县| 鄂伦春自治旗| 文安县| 明溪县| 赤壁市| 旺苍县| 梨树县| 锡林郭勒盟| 乳源| 黔东| 泰安市| 贵港市| 偃师市| 英德市| 城口县| 宝应县| 搜索| 玛曲县| 柳州市| 台北市| 扶风县| 北碚区| 滕州市| 澜沧| 县级市| 威远县| 尤溪县| 景东| 桂阳县|