Skip to content Skip to sidebar Skip to footer

Why It Doesn't Replace Correctly If I Run Multiple Replace Checks?

I am replacing smile character like :) to images. If I use only var yorum4 = 'hello :)'; yorum4 = yorum4.replace(/(:\))/g, ''); It re

Solution 1:

Your /:\D/ pattern matches a colon and any non-digit symbol and can thus match a :/ inside a protocol part of an URL.

If you meant a :D smiley, just use /:D/. Same goes for all the literal letters and digits: do not escape them. Also, there is no point using capturing groups around whole patterns, if you need to reference the match values in the replacement pattern, just use $& (not $1).

var yorum4 = "hello :)";
yorum4 = yorum4.replace(/:\)/g, "<img class='smileys' src='i.png' \/>");
yorum4 = yorum4.replace(/;\)/g, "<img class='smileys' src='j.png' \/>");
yorum4 = yorum4.replace(/:p/g, "<img class='smileys' src='b.png' \/>");
yorum4 = yorum4.replace(/:P/g, "<img class='smileys' src='b.png' \/>");
yorum4 = yorum4.replace(/:D/g, "<img class='smileys' src='c.png' \/>");
yorum4 = yorum4.replace(/:d/g, "<img class='smileys' src='c.png' \/>");
yorum4 = yorum4.replace(/:'\(/g, "<img class='smileys' src='d.png' \/>");
yorum4 = yorum4.replace(/:\*/g, "<img class='smileys' src='a.png' \/>");
yorum4 = yorum4.replace(/<3/g, "<img class='smileys' src='f.png' \/>");
yorum4 = yorum4.replace(/:o/g, "<img class='smileys' src='he.png' \/>");
yorum4 = yorum4.replace(/:O/g, "<img class='smileys' src='e.png' \/>");
yorum4 = yorum4.replace(/:\(/g, "<img class='smileys' src='s.png' \/>");
console.log(yorum4);

Another hint: you might want to use word boundaries and non-word boundaries, like /\B:\)\B/ or /\B:D\b/ (adding non-word boundary \B before/after non-word chars and word boundaries \b before/after word chars) to match these smileys as "whole words", but it is difficult to say without the actual data.

Solution 2:

Just a spin of Wiktor's answer (which is the one you should accept, not this one) that incorporates the technique I mentioned in this comment and originally demonstrated in this fiddle:

var yorum4 = "hello :)";
var smiles = {
    ":)":   "i.png",
    ";)":   "j.png",
    ":p":   "b.png",
    ":P":   "b.png",
    ":D":   "c.png",
    ":d":   "c.png",
    ":'\(": "d.png",
    ":*":   "a.png",
    "<3":   "f.png",
    ":o":   "he.png",
    ":O":   "e.png",
    ":(":   "s.png"
};
yorum4 = yorum4.replace(/:\)|;\)|:p|:P|:D|:d|:'\(|:\*|<3|:o|:O|:\(/g, function(m) {
    return"<img class='smileys' src='" + smiles[m] + "' \/>";
});
console.log(yorum4);

Of course, that version makes you list each smiley token twice. You could build the regex from the keys of the smiles object, being sure to handle any necessary escaping. I leave it as an exercise to the reader...

Post a Comment for "Why It Doesn't Replace Correctly If I Run Multiple Replace Checks?"