Adam Pietrasiak
Adam Pietrasiak

Reputation: 13184

Javascript - replace string basing on array

I've got

mystring = "Google" and I've got array

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

I want to do something like

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

So it would return G<b>o</b><b>o</b>gl<b>e</b> - every comming matching letter from array is wrapped in tag.

I also have proper regexp for it /.*?(o).*?(o).*(e).*/i That have matching groups for o followed by o followed by e.

Those arrays and strings are auto generated (fuzzy search) so I'm not able to say how big array and strings will be. I only know the letters to look in the string.

Upvotes: 1

Views: 71

Answers (3)

anubhava
anubhava

Reputation: 784958

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;
for (var i 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 to use of negative lookahead (?!<\/b>) same letter is not replaced twice.

JSFiddle

Upvotes: 2

pawel
pawel

Reputation: 36965

So I came up with something like this:

var boldByArray = function( string, array ){
    var result = [];
    string.split('').forEach( function( letter ){
        if( array.indexOf( letter ) == 0 ){
             result.push( '<b>' + array.shift() +'</b>' );
        }
        else {    
            result.push( letter );
         }
    });
    return result.join('');
}

The result for array boldByArray('google', ['e','g','o']) will be Googl<b>e</b> because you want to respect the order, so it finds the e, then looks for g and o after that e which never comes. boldByArray('google', ['x','g','o']) will be just google, because there's no x.

http://jsfiddle.net/wuSaE/1/

Updated with fuzzy matching demo gathered from comments you've provided: http://jsfiddle.net/wuSaE/3/

Upvotes: 0

Toto
Toto

Reputation: 91375

Here is my way to go:

var tmp = mystring;
for (l in myarray) {
    tmp = tmp.replace(new RegExp('('+myarray[l]+'(?:\\B|$))'), '<b>$1</b>');
}

Console:

G<b>o</b><b>o</b>gl<b>e</b>

The (?:\\B|$) makes the regex not producing G<b><b>o</b></b>ogl<b>e</b>

You could also use:

new RegExp('('+myarray[l]+'(?!<))')

Upvotes: 1

Related Questions