Reputation: 2741
I've been trying different functions to replace any [email protected]
inside a contentEditable
DIV without success. There's either problems with the regex or with the fact that [String].replaceAll
isn't an existing prototype in Chrome so I need to use any replaceAll
I find on the web.
What should be the cross-browser (Chrome/WebKit/Moz) algorithm to replace all emails inside a string with a custom pattern?
Upvotes: 1
Views: 544
Reputation: 72927
replaceAll
isn't a standard function, indeed, but a regex should work:
Something simple like this:
[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}
Can already work pretty well:
var s = "[email protected] is a sample email address with an @, as is [email protected]";
s.replace(/([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/ig, '<tag>$1</tag>');
// "<tag>[email protected]</tag> is a sample email address with an @, as is <tag>[email protected]</tag>";
# Match:
# ( --> Start group
# [A-Z0-9._%+-]+ --> one or more characters within the specified range,
# @ --> Followed by an `@`,
# [A-Z0-9.-]+ --> Followed by some more characters,
# \. --> Followed by an dot,
# [A-Z]{2,} --> followed by 2 or more letters,
# ) --> End group.
# ig --> (i)gnore case, (g)lobal.
# In the replacement:
# $1 --> Content of the first pair of `()`
Upvotes: 4