Amigos Amigos - 1 year ago 85
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 Source


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download