[英]replace first n occurrence of a string
I have a string var with following: 我有以下字符串var:
var str = getDataValue();
//str value is in this format = "aVal,bVal,cVal,dVal,eVal"
Note that the value is separated by ,
respectively, and the val is not fixed / hardcoded. 注意,值是通过分离
,
分别与VAL是不固定的/硬编码。 How do I replace only the bVal everytime? 如何每次仅更换bVal?
If you use string as the regex, escape the string to prevent malicious attacks: 如果将字符串用作正则表达式,请转义该字符串以防止恶意攻击:
RegExp.escape = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
new RegExp(RegExp.escape(string));
var str = "aVal,bVal,cVal,dVal,eVal"; var rgx = 'bVal'; var x = 'replacement'; var res = str.replace(rgx, x); console.log(res);
Try this 尝试这个
var targetValue = 'bVal';
var replaceValue = 'yourValue';
str = str.replace(targetValue , replaceValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.