Javascript - replace string basing on array -


i've got

mystring = "google" , i've got array

myarray = ["o", "o", "e"]

i want

mystring.replace(myarray, "<b>$</b>")  

so return g<b>o</b><b>o</b>gl<b>e</b> - every comming matching letter array wrapped in tag.

i have proper regexp /.*?(o).*?(o).*(e).*/i have matching groups o followed o followed e.

those arrays , strings auto generated (fuzzy search) i'm not able how big array , strings be. know letters in string.

you can do:

mystring =  "google"; myarray = ["o", "o", "e"];  var r = mystring.replace(new regexp( '(' + myarray.join('|') + ')', 'g'), "<b>$1</b>"); //=> g<b>o</b><b>o</b>gl<b>e</b> 

edit: based on discussions below:

mystring =  "google"; myarray = ["g", "o", "e"];  var r = mystring; (var in myarray) {     r = r.replace(new regexp('('+myarray[i]+')(?!<\\/b>)', "i"), "<b>$1</b>"); } console.log(r); // <b>g</b><b>o</b>ogl<b>e</b> 

ps: due use of negative lookahead (?!<\/b>) same letter not replaced twice.

jsfiddle


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -