Home > Back-end >  String match one or more numbers with a # - Javascript / regex
String match one or more numbers with a # - Javascript / regex

Time:07-09

I am trying to match a part of a string with another string. In string one I have a larger amount of text that has the desired string within. In string two I have a part of the desired string with the numbers replaced with '#'.

How can I match any numbers in the same position of the #?

I am guessing that there would be a regex that does this but I can't figure it out.

Example

Str1 = "Adds 2 to 5 Cold Damage Adds 20 to 50 Fire Damage Adds 1 to 100 Lightning Damage"    

Str2 = "Adds # to # Fire Damage" 

res = "Adds 20 to 50 Fire Damage"

CodePudding user response:

Replace the # with \d to match a number there, and convert that to a regular expression.

let Str1 = "Adds 2 to 5 Cold Damage Adds 20 to 50 Fire Damage Adds 1 to 100 Lightning Damage";
let Str2 = "Adds # to # Fire Damage";
let re = new RegExp(Str2.replaceAll('#', '\\d '));
let res = Str1.match(re);
if (res) {
  console.log(res[0]);
}

  • Related