Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  46] [ 6]  / answers: 1 / hits: 147296  / 7 Years ago, sun, april 9, 2017, 12:00:00

I'm trying to replace all full stops in an email with an x character - for example [email protected] would become myxemail@emailxcom. Email is set to a string.

My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's.

I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code:



let re = .;
let new = email.replace(/re/gi, x);


I've also tried



re = /./gi;
new = email.replace(re, x);


If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong.



** Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue!


More From » string

 Answers
108

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)




[#58217] Thursday, April 6, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
;