I want to have a Javascript function that uses regular expressions to add things to the borders of certain words in a text.
Example, I want to replace this:
The swift Indian bat happily ate thistle and kiwi. The stork played the saxophone...
... for the following, knowing that the keywords are swift , thistle and kiwi :
The <b>fast</b> Indian bat happily ate <b>thistle<b> and <b>kiwi</b>. The stork played the saxophone...
For this we are going to use the Javascript
replace
del methodString
, which receives two parameters, one is the regular expression (pattern), and the other is the replacement expression.The first argument contains the keywords, they must be grouped using the form
(?:lista)
, among other things, to save memory, and separated by the alternation operator|
, in this case, swift, vermilion or kiwi. Also, to separate in complete words, it is used\b
at the beginning and at the end of the word.It is as follows:
The second argument has a dollar sign followed by an American y (ampersand), is written
$&
, which returns all the text that was matched, and we can add the borders we want to the left and right, in this case, simulating a bold label<b>clave</b>
.The action to replace is as follows.
End code: