Add borders to words in regular expressions

11

I want to have in Javascript a function that uses regular expressions to add things to the edges of certain words in a text.

Example, I want to replace this:

  

The swift Indian bat ate happy cardillo and kiwi. The stork played the saxophone ...

... for the following, knowing that the keywords are fast , cardillo and kiwi :

  

The < b > veloz < / b > Indian bat ate happily cardillo & bt; and < b > kiwi < / b > The stork played the saxophone ...

    
asked by ArtEze 25.03.2017 в 00:12
source

1 answer

14

For this we are going to use the method replace of the String of Javascript , which receives two parameters, one is the regular expression (pattern), and the other is the expression of replacement.

The first argument contains the keywords, you have to group them using the form (?:lista) , among other things, to save memory, and separated by the alternation operator | , in this case, fast, cardillo or kiwi. Also, to separate in whole words, use \b at the beginning and end of the word.

It looks like this:

/\b(?:veloz|cardillo|kiwi)\b/gi

The second argument has a weights sign followed by a and American (ampersand), it is written $& , which returns all the text with which it coincided, and we can add the edges that we want to the left and to the right, in this case, simulating a bold label <b>clave</b> .

<b>$&</b>

The action to be replaced is as follows.

texto.replace(/\b(?:veloz|cardillo|kiwi)\b/gi,"<b>$&</b>")

Final code:

function agregar_borde(texto,claves,izquierdo,derecho)
{
  var salida = claves.join("|")
  var expresión = new RegExp("\b(?:"+salida+")\b","gi")
  return texto.replace(expresión,izquierdo+"$&"+derecho)
}

var texto = "El veloz murciélago hindú comía feliz cardillo y kiwi."+
  " La cigüeña tocaba el saxofón..."

var palabras_claves = ["veloz","cardillo","kiwi"]
  
var izquierdo="<b>"
var derecho="</b>"

var resultado=agregar_borde(texto,palabras_claves,izquierdo,derecho)

document.write(texto)
document.write("<p/>")
document.write(resultado)

console.log(texto)
console.log(resultado)
    
answered by 25.03.2017 / 00:12
source