xnanitox
xnanitox

Reputation: 495

Replace and Concat an image HTML String

I have an array named Sport with almost 20 items and I need to replace an image HTML string with global replacement (/string/g), my string contains HTML tags. This is an example:

//Sports array
var sport = ['soccer','tennis','pool','basketball'];

//Original string
var original = 'Hello, do you play <img width="20" src="img/soccer.png"/> ?';

//New string
var newstring;

//If original string contains an image html of some sports from array,replace with :sport[item]:
for (var i = 0; i < sport.Length; i++)
{
   newstring = original.replace('/<img width="20" src="img\/icons\/'+sport[i]+'.png"/>/g',':'+sport[i]+':');
}

So, recap... I need to replace this

<img width="20" src="img/soccer.png"/>

To this

:soccer:

The result should be: Hello, do you play :soccer:?

Upvotes: 0

Views: 247

Answers (1)

Apolo
Apolo

Reputation: 4050

You have to replace this :

newstring = original.replace('/<img width="20" src="img\/icons\/'+sport[i]+'.png"/>/g',':'+sport[i]+':');

to this :

newstring = original.replace(new RegExp('<img width="20" src="img\/icons\/'+sport[i]+'.png"\/>', 'g'),':'+sport[i]+':');

because you can't concatenate string in "inline" regex (if someone knows the right name, please comment) :

// no quotes around pattern
newString = myString.replace(/pattern/g, "foo")

You should have a look at this answer : Replacing all occurrences of a string in JavaScript


Edit :

If you have troubles with special characters (from the answer quoted) :

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}


// Use :
var newString = replaceAll(myString,"pattern", "replace_with_this");

In your example :

for (var i = 0; i < sport.length; i++)
{
    newstring = replaceAll(
                    // original String
                    original,
                    // pattern
                    '<img width="20" src="img/icons/'+sport[i]+'.png"/>',
                    // replace with :
                    ':'+sport[i]+':');
}

note: in replaceAll you don't have to escape your pattern, it is done by the escapeRegExp function

Upvotes: 1

Related Questions