简体   繁体   中英

How to replace strings from an array

I'm working on a piece of code that uses regex expressions to do a find/replace for emoticons in a chat. However, I want to use the same array of values and output them as a reference.

The regex works fine for my searches, but when I tried to do a replace on the regex search string before I output it for my help, I still end up with a slash.

:\)
:\(

var emotes = [];
emotes[0] = new Array(':\\\)', 'happy.png');
emotes[1] = new Array(':\\\(', 'sad.png');

function listEmotes(){
    var emotestext = '';
    for(var i = 0; i < emotes.length; i++){

        //Tried this and it doesn't seem to work
        //var emote = emotes[i][0];
        //emote.replace('\\', '');

        emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
    }

    return emotestext;
}

Your problem is that str.replace doesn't change the original variable but instead returns a new one. Try this out:

var emotes = [
    [':\\\)', 'happy.png'],
    [':\\\(', 'sad.png']
];

function listEmotes(){
    var emotestext = '';
    for(var i = 0; i < emotes.length; i++){
        var emote = emotes[i][0].replace('\\', ''); // See what I did here?

        emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
    }

    return emotestext;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM