简体   繁体   English

如何用javascript替换字符串?

[英]How to replace strings with javascript?

I have this function: 我有这个功能:

function emoticons(text){
    var url = "http://www.domain.it/images/smilies/";
    var emt = {
       ":D"  : 'icon_e_biggrin.gif',
       ":-D" : 'icon_e_biggrin.gif',       
       ":)"  : 'icon_e_smile.gif',
       ":-)" : 'icon_e_smile.gif',       
       ";)"  : 'icon_e_wink.gif',
       "';-)" : 'icon_e_wink.gif',

       ":("  : 'icon_e_sad.gif',
       ":-(" : 'icon_e_sad.gif',
       ":o"  : 'icon_e_surprised.gif',
       ":?"  : 'icon_e_confused.gif',
       "8-)" : 'icon_cool.gif',

       ":x"  : 'icon_mad.gif',
       ":P"  : 'icon_razz.gif'
    };

    for (smile in emt){        
        text   = text.replace(smile, '<img src="' + url + emt[smile] + '" class="emoticons" />');
    }

    return (text);
}

As you know .replace() convert the first occurence, how to replace more then one emoticon inside the text? 如你所知.replace()转换第一次出现,如何在文本中替换多个表情符号? How to change this function? 如何更改此功能?

Thank you very much! 非常感谢你!

You could translate each emoticon string to a global regular expression, which will replace all occurrences when used with the String#replace method: 您可以将每个表情符号字符串转换为全局正则表达式,当与String#replace方法一起使用时,它将替换所有出现的表达式:

function emoticons(text){
  var url = "http://www.domain.it/images/smilies/";
  var emt = {
    /\:D/g:   'icon_e_biggrin.gif',
    /\:\-D/g: 'icon_e_biggrin.gif',
//...

You'll have to be careful about escaping special characters in the emoticon text though. 但是,你必须要小心逃避表情符号文本中的特殊字符。

maerics' answer is a fairly small change to your existing function that should do the trick. 对于你现有的功能来说, maerics的回答是一个相当小的改变。 If the text you're doing these replacements in is large, though, you might consider flipping things on their head and using a regex alternation and a replacement function. 但是,如果你正在进行这些替换的文本很大,你可能会考虑在头上翻转并使用正则表达式替换和替换功能。

Regex alternations look like this: /A|B|C/ , which tells the regex engine to look A or B or C. The function you give to String#replace receives the matching text as an argument, so it can then look up the relevant replacement in a map: 正则表达式的替换如下所示: /A|B|C/ ,它告诉正则表达式引擎看A B C.你给String#replace的函数接收匹配的文本作为参数,这样它就可以查找相关的地图替换:

function emoticons(text){
    // The base URL of all our smilies
    var url = "http://www.domain.it/images/smilies/";

    // A regex alternation that looks for all of them (be careful to use escapes
    // where necessary)
    var searchFor = /:D|:-D|:\)|:-\)|;\)|';-\)|:\(|:-\(|:o|:\?|8-\)|:x|:P/gi;

    // A map mapping each smiley to its image
    var map = {
        ":D"  : 'icon_e_biggrin.gif', // Capped version of the next
        ":d"  : 'icon_e_biggrin.gif', // Lower case version of the previous
        ":-D" : 'icon_e_biggrin.gif', // Capped version of the next
        ":-d" : 'icon_e_biggrin.gif', // Lower case version of the previous
        ":)"  : 'icon_e_smile.gif',
        ":-)" : 'icon_e_smile.gif',
        ";)"  : 'icon_e_wink.gif',
        "';-)" : 'icon_e_wink.gif',

        ":("  : 'icon_e_sad.gif',
        ":-(" : 'icon_e_sad.gif',
        ":O"  : 'icon_e_surprised.gif', // Capped version of the next
        ":o"  : 'icon_e_surprised.gif', // Lower case version of the previous
        ":?"  : 'icon_e_confused.gif',
        "8-)" : 'icon_cool.gif',

        ":X"  : 'icon_mad.gif',    // Capped version of the next
        ":x"  : 'icon_mad.gif',    // Lower case version of the previous
        ":P"  : 'icon_razz.gif',   // Capped version of the next
        ":p"  : 'icon_razz.gif'    // Lower case version of the previous
    };

    // Do the replacements
    text = text.replace(searchFor, function(match) {
        var rep;

        // Look up this match to see if we have an image for it
        rep = map[match];

        // If we do, return an `img` tag using that smiley icon; if not, there's
        // a mis-match between our `searchFor` regex and our map of
        // smilies, but handle it gracefully by returning the match unchanged.
        return rep ? '<img src="' + url + rep + '" class="emoticons" />' : match;
    });

    return (text);
}

Doing this lets you only loop through the string once and build a single replacement string, rather than looping through it for each smiley and building multiple interim strings. 这样做只允许您循环遍历字符串一次并构建一个替换字符串,而不是为每个笑脸循环遍历它并构建多个临时字符串。

For smallish bits of text it won't matter and the complexity (maintaining each smiley in two different places) may not be worth it, but for large texts it may be. 对于一小部分文本来说无关紧要,复杂性(在两个不同的地方保持每个笑脸)可能不值得,但对于大文本来说可能是不值得的。

Another solution is to create a RegExp with the "g" modifier for each string. 另一个解决方案是为每个字符串创建一个带有“g”修饰符的RegExp。 And since this function may be run more than once par pageload, you should create emt and the regexps only once: 并且由于此函数可能不止一次运行par pageload,因此您应该只创建一次emt和regexp:

var emoticons = (function () {
    var url = "http://www.domain.it/images/smilies/";
    var emt = {
       ":D"  : 'icon_e_biggrin.gif',
       ":-D" : 'icon_e_biggrin.gif',       
       ":)"  : 'icon_e_smile.gif',
       ":-)" : 'icon_e_smile.gif',       
       ";)"  : 'icon_e_wink.gif',
       "';-)" : 'icon_e_wink.gif',

       ":("  : 'icon_e_sad.gif',
       ":-(" : 'icon_e_sad.gif',
       ":o"  : 'icon_e_surprised.gif',
       ":?"  : 'icon_e_confused.gif',
       "8-)" : 'icon_cool.gif',

       ":x"  : 'icon_mad.gif',
       ":P"  : 'icon_razz.gif'
    };

    var patterns = [];
    for (smile in emt) {
        patterns.push([
            // escaping string special characters by hand
            // case-insensitive to match :p :d etc.
            new RegExp(smile.replace(/([\(\)\[\]\{\}\.\?\^\$\|\-])/g, "\\$1"), "gi"),
            '<img src="' + url + emt[smile] + '" class="emoticons" />'
        ]); 
    }

    // this is the function that will be referenced by the variable emoticons
    return function (text) {
        for(var i=0; i<patterns.length; i++) {
            text = text.replace(patterns[i][0], patterns[i][1]);
        }
        return text;
    }

})();

Here is a demo: http://jsfiddle.net/gjfzf/2/ 这是一个演示: http//jsfiddle.net/gjfzf/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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