Amigos Amigos - 1 month ago 7
jQuery Question

replace first n occurrence of a string

I have a string var with following:

var str = getDataValue();
//str value is in this formate = "aVal,bVal,cVal,dVal,eVal"


Note that the value is separated by
,
respectively, and the val is not fixed
How do I replace only the bVal everytime?

Answer

EDIT

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);