The replace()
function (or method, if you consider it as a member of the String
object) has a special feature that turns out to be very useful when it comes to replace plain strings with HTML elements: it accepts a callback function that can be used together with regular expressions matching groups. For example, you have some text inside an element and you want to replace it with a strong
element in order to emphasize it. You can use replace()
as follows:
var re = /javascript/gmi; elementContent.replace(re, function($1) { return '<strong>' + $1 + '</strong>; });
The group $1
contains the first matches of our regular expression. We pass it as a parameter of the callback function of replace()
and we use it to substitute our string with the desired HTML element which, in turns, contains the original string. Note that in this case browsers will interpret our parameter correctly, because it's been defined inside the callback function body as its sole argument. Otherwise, JavaScript interpreters may get confused by it and will return an error saying that you've declared an undefined
variable.
Good article!
You are snippets for tests and results for that code
with some elementContent i would like understand better this implementation!
Thanks!
Josenildo
Basically, $1 is a reference to the match that you get with the regular expression. So when you pass that reference to the callback function, then it will be used for replacement. Thanks for the comment. :-)