Amigos Amigos - 8 months ago 37
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?



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