替换String中的内容所需的Jquery函数

时间:2012-11-17 02:34:25

标签: javascript

我有一个textarea,用户可以在其中键入内容,还包括表情符号,如:)或;)

当按下“已发送”时,需要解析textarea字符串以将任何表情符号转换为<img>以供显示。

我可以很容易地生成一个表情符号列表,并有相关的图像,如:

 ':)' - '<img src="/images/happy.jpg"/>'
 ';)' - '<img src="/images/wink.jpg"/>'

我认为上面的内容可以放入一个关联数组中。

有人能指出我正确的方向来创建表情符号和html img标签的关联数组,然后解析一个字符串以用html img标签替换匹配的符号吗?

还有一个更好的方法吗?

三江源

4 个答案:

答案 0 :(得分:5)

你实际上已经描述了这种行为:

var map = {
    ':)':   '<img src="/images/happy.jpg"/>',
    ';(':   '<img src="/images/wink.jpg"/>'
},
text    = document.getElementsByTagName('textarea')[ 0 ].value;

Object.keys( map ).forEach(function( ico ) {
    // escape special characters for regex
    var icoE   = ico.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    // now replace actual symbols
    text       = text.replace( new RegExp(icoE, 'g'), map[ico] );
});

示例:http://jsfiddle.net/DBfpw/2/


修改
为了创建有效的正则表达式,我们需要转义)(

注意
上面的代码段包含 ECMAscript5 特色代码。如果您需要在旧版浏览器上运行,请确保包含 ES5 Shim 库。

注2
抱歉,上面的代码包含任何jQuery代码,因为它不是必需的。

答案 1 :(得分:2)

我会创建一个对象数组,如:

var emoticons = [{regex: /:\)/g, image: "happy"},
                 {regex: /;\)/g, image: "wink"},
                 etc...]  

然后迭代该数组以进行替换

for(var i = 0; i < emoticons.length; i++) {
    str = str.replace(emoticons[i].regex, 
        '<img src="/' + emoticons[i].image + '.jpg"/>');
}

答案 2 :(得分:2)

您可以在用户输入时使用JavaScript替换表情符号。但是将带有替换表情符号的字符串发送到服务器脚本并不是一个好方法。 这不是安全的方式 - 在提交到服务器端脚本之前,任何人都可以在客户端替换您的内容。保存<img src="images/sad.jpg">而不是:-(或者更换一些会更好。存储的数据更少+您可以更轻松地将其替换为新的图像/图像位置和任何其他字符串。

因此,一种方法是将字符串发布到服务器端脚本以存储在数据库中。对于视图渲染(先前发送到浏览器),您可以使用函数(如下所示)将每个表情字符串替换为特定图像:

<?php
    $text = 'Hey :-), how are you doing bro? Having some fun :-D? Lets meet :-(';

    $smileys = array(
        ':-)' => 'happy',
        ':-(' => 'sad',
        ':-D' => 'tongue'
    );

    foreach($smileys as $key => $value) { 
            $text =  str_replace($key, '<img srce="images/'.$value .'.jpg">', $text);
    }

    echo $text;
?>

答案 3 :(得分:1)

// Start off by listing all supported emoticons and their names
var emoticons = {
    ":)": "smile",
    ":P": "tongue",
    ":(": "sad",
}, regex = [];

// push a regex for each one (:\)) onto an array.  Escape each special character
// each component is wrapped in unescaped parentheses to *capture* the token
// dynamically building this is optional -
// you may want to generate the regex once and use the literal
for(var emoticon in emoticons) {
    if(emoticons.hasOwnProperty(emoticon)) {
        regex.push("("+emoticon.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")+")");
    }
}

//join the array to form a string and use the regex OR operator.
regex = new RegExp(regex.join("|"), "g");
// Now the regex looks like this - /(:\))|(:P)|(:\()/g

// String replace function also takes a function as the second parameter.
// The function takes the captured text, (what we put in parenthesis earlier)
// and you can use it to refer to the emoticon hash at the beginning.
// Then you return the desired replaced text.
text = text.replace(regex, function(captured) {
    return "<img src='"+emoticons[captured]+".jpg'/>";
});
这项技术的

jsFiddle演示