假设有一个字符串,可能'Good Morning'
也可能是'Hello World'
,我想将第五个字符,替换成'-'
。
因为字符串虽然可以像数组那样获取某一位置字符'Hello World'[4]
,但是不能像数组那样直接修改某一位置的字符'Hello World'[4] = '-'
,这样是行不通的,但是可以把它切分成数组,修改某一位置的值,然后在合并回来。
方法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替换字符串中所有指定的字符
第一次发现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>
总结
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CUE】