Lelly
Lelly

Reputation: 968

Matching values in arrays and replacing a string

Im trying to build a little converter "html to BBcode" for images only, and I need help !

Exemple string:

var str = 'Hello ! <img src="/pathHere/party.png"><img src="/pathHere/sun.png">';

Im doing a regEx to find if there are any images in the string

var reg = new RegExp(/(\w+)\.(jpg|png|gif)/gi);
var matches = str.match(reg);
console.log(matches);

In this exemple, it would give me an arraylike this:

["party.png", "sun.png"]

I have an associative array like:

var itemsToConvert = {
    'party.png' : ':party:',
    'sun.png'   : ':sun:',
    'cloud.png' : ':cloud:',
}

What I want to achieve:

So, in this exemple my string would be

var convertedString = 'Hello ! :party: :sun.png:'

Any help would be greatly appreciated.

Thanks

Upvotes: 0

Views: 40

Answers (2)

Ananth
Ananth

Reputation: 4397

Using plain javascript:

var str = 'Hello ! <img src="/pathHere/party.png"><img src="/pathHere/sun.png">';
var matches = str.match(new RegExp(/(\w+)\.(jpg|png|gif)/gi));
var itemsToConvert = {
    'party.png' : ':party:',
    'sun.png'   : ':sun:',
    'cloud.png' : ':cloud:',
}

for (m in matches) {
    m = matches[m];
    if (itemsToConvert[m] !== undefined) {
        var r = new RegExp("<img(.*?)" + m + "\\\">");
        str = str.replace(r, itemsToConvert[m]);
    }
}

console.log(str);

// Output: Hello ! :party::sun:

You can add spaces between the codes if you wish.

Upvotes: 1

Peter Wagener
Peter Wagener

Reputation: 2092

Best bet would be to use Underscore JS. There are lots of methods there for doing this sort of stuff. Your problem, for instance, could be solved by:

matches = ["party.png", "sun.png"];
var itemsToConvert = {
    'party.png' : ':party:',
    'sun.png'   : ':sun:',
    'cloud.png' : ':cloud:',
};

// Extract the keys from the associative array
var keys = _.keys(itemsToConvert);

var toConvertString = "Hello ! party.png  sun.png ";

var convertedString = toConvertString;

// For each key, replace any matches with the value from the associative array
_.each(keys, function(key) {
    var value = itemsToConvert[key];
    convertedString = convertedString.replace(key, value);
});

console.log(convertedString);  // <<== returns "Hello ! :party:  :sun: "

This doesn't perfectly match your requested string, but I'm not completely sure where you're getting the associative array from. Hopefully it gets you close enough.

Upvotes: 1

Related Questions