David David - 1 month ago 8
Javascript Question

How to replace all the character of string with reference of particular index

How to replace all the character of string with reference of particular index.

I have a string like

var str = "A1 B1C2"


Now I want to check what is the character in 1st index

var charAtFirst = str.charAt(1);


so I am getting 1.

Now I want to replace all the character which is having value 1. how to do that. Thanks for help.

Answer

Generate RegExp using the string while creating you need to escape the special meaning characters in the string. After generating the RegExp use String#replace method.

var str = "A1 B1C2";
var charAtFirst = str.charAt(1);

console.log(
  str.replace(new RegExp(charAtFirst.replace(/[|\\{}()[\]^$+*?.]/, '\\$&'), 'g'), '')
);


UPDATE 1 : If you want to remove number greater than a particular number then get all numbers and replace by comparing with the number. You can use String#replace method with a callback function.

var str = "A1 B1C2";
var charAtFirst = +str.charAt(1);

console.log(
  str.replace(/\d+/g, function(m) {
    return +m > charAtFirst ? '' : m;
  })
);


UPDATE 2 : If you want to increment the character then do it like.

var str = "A1 B1C2";
var charAtFirst = str.charAt(1);

console.log(
  str.replace(new RegExp(charAtFirst.replace(/[|\\{}()[\]^$+*?.]/, '\\$&'), 'g'), (+charAtFirst) + 1)
);