【问题标题】:How to replace strings from an array如何替换数组中的字符串
【发布时间】:2010-09-05 18:37:00
【问题描述】:

我正在编写一段代码,它使用正则表达式来查找/替换聊天中的表情符号。但是,我想使用相同的值数组并将它们作为参考输出。

正则表达式可以很好地用于我的搜索,但是当我尝试在输出正则表达式搜索字符串以寻求帮助之前对其进行替换时,我仍然会得到一个斜杠。

:\)
:\(

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;
}

【问题讨论】:

    标签: javascript regex string backslash


    【解决方案1】:

    您的问题是 str.replace 不会更改原始变量,而是返回一个新变量。试试这个:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-25
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2010-09-28
      • 1970-01-01
      • 2011-01-21
      相关资源
      最近更新 更多