JS如何替换字符串中指定位置的字符

发布时间:2020-07-21 10:35:24 作者:小猪
来源:亿速云 阅读:1917

这篇文章主要为大家展示了JS如何替换字符串中指定位置的字符,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

假设有一个字符串,可能'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 &#63; "gi": "g")), replaceWith); 
  } else { 
    return this.replace(reallyDo, replaceWith); 
  } 
} 
</script> 

以上就是关于JS如何替换字符串中指定位置的字符的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 如何批量替换字符串中的某个特定字符?
  2. 如何替换字符串中的空格

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js 符串

上一篇:windows 10 Quick Assist 远程协助工具

下一篇:关于编程这件事

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》