如何使用多种方法在JS中替换字符串指定位置的字符?
- 内容介绍
- 文章标签
- 相关推荐
本文共计710个文字,预计阅读时间需要3分钟。
假设有一个字符串,可能包含Good Morning也可能包含Hello World,我想将第五个字符替换成-。由于字符串不能像数组那样直接通过索引访问,我们需要先将字符串转换为字符数组,进行替换操作,然后再将字符数组转换回字符串。以下是如何操作的示例代码:
pythondef replace_fifth_char(input_str): if len(input_str) <5: return input_str # 将字符串转换为字符数组 chars=list(input_str) # 替换第五个字符 chars[4]='-' # 将字符数组转换回字符串 return ''.join(chars)
示例使用input_str=Good Morningresult=replace_fifth_char(input_str)print(result)
input_str=Hello Worldresult=replace_fifth_char(input_str)print(result)
假设有一个字符串,可能'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>
总结
到此这篇关于JS替换字符串中指定位置的字符的文章就介绍到这了,更多相关js替换字符内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
本文共计710个文字,预计阅读时间需要3分钟。
假设有一个字符串,可能包含Good Morning也可能包含Hello World,我想将第五个字符替换成-。由于字符串不能像数组那样直接通过索引访问,我们需要先将字符串转换为字符数组,进行替换操作,然后再将字符数组转换回字符串。以下是如何操作的示例代码:
pythondef replace_fifth_char(input_str): if len(input_str) <5: return input_str # 将字符串转换为字符数组 chars=list(input_str) # 替换第五个字符 chars[4]='-' # 将字符数组转换回字符串 return ''.join(chars)
示例使用input_str=Good Morningresult=replace_fifth_char(input_str)print(result)
input_str=Hello Worldresult=replace_fifth_char(input_str)print(result)
假设有一个字符串,可能'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>
总结
到此这篇关于JS替换字符串中指定位置的字符的文章就介绍到这了,更多相关js替换字符内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

