Replace all instances of character in string in typescript?
Your second example is the closest. The first problem is your variable name, new
, which happens to be one of JavaScript's reserved keywords (and is instead used to construct objects, like new RegExp
or new Set
). This means that your program will throw a Syntax Error.
Also, since the dot (.
) is a special character inside regex grammar, you should escape it as \.
. Otherwise you would end up with result == "xxxxxxxxxxxxxxxxxx"
, which is undesirable.
let email = "[email protected]"
let re = /\./gi;
let result = email.replace(re, "x");
console.log(result)
You can try split()
and join()
method that was work for me. (For normal string text)
It was short and simple to implement and understand.
Below is an example.
let email = "[email protected]";
email.split('.').join('x');
So, it will replace all your .
with x
. So, after the above example, email
variable become myxemail@gmailxcom