0

I'm using the <string>.replace(/x/g,"y") to replace all instances of a character in a string to a different character, and I get exactly what I need.

My problem is with the syntax of the pattern (i.e. /x/g) that causes issues in a small post-processor I developed for all the javascript files included in my project.

The solution to my problem can be to encapsulate the string replacement within an isolated file that would not undergo post-processing.

(What post-processing does and why I use it is not important here)

My question: Suppose I create a function Switch_All_Chars(In_Str,Old_C,New_C) that replaces all instances of Old_C by New_C in In_str returning the updated string, and it would loo like:

function Switch_All_Chars(In_Str,Old_C,New_C) {
    pat = /Old_C/g ;
    return In_Str.replace( pat , New_C) ;
}

This would not work because par is not properly defined. Is there a syntax that would allow the definition of the pattern using a variable?

Thanks.

FDavidov
  • 3,202
  • 5
  • 19
  • 48

1 Answers1

2

Use RegExp constructor:

var pat = new RegExp(Old_C, "g")
Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155