用正则表达式替换JavaScript中的Smiley

本文关键字:中的 Smiley JavaScript 替换 正则表达式 | 更新日期: 2023-09-27 18:17:58

我刚刚看到下面的帖子使用regex c#将emoticon替换为tweet中的word,其中smiley被解析并替换为一些自定义文本:

static string ReplaceSmile(Match m) {
    string x = m.ToString();
    if (x.Equals(":)")) {
        return "happy";
    } else if (x.Equals(":(")) {
        return "sad";
    }
    return x;
}
static void Main() {
    string text = "Today is a sunny day :). But tomorrow it is going to rain :(";
    Regex rx = new Regex(@":[()]");
    string result = rx.Replace(text, new MatchEvaluator(ReplaceSmile));
    System.Console.WriteLine("result=[" + result + "]");
}

你能帮助我通过JavaScript实现相同的说我有笑脸在JavaScript变量的字符串,如何实现我们在c#中所做的相同的行为?

用正则表达式替换JavaScript中的Smiley

var result = "hello :)".replace(/:[()]/, "replacement");

查看JavaScript字符串替换方法了解更多细节。

在你的情况下,我可能不会使用正则表达式。我只需要这样做-

var text = "Today is a sunny day :). But tomorrow it is going to rain :(";
text = text.replace(":)", "happy");
text = text.replace(":(", "sad");
// text is "Today is a sunny day happy. But tomorrow it is going to rain sad"

你可以使用"replace"方法的重载:

var text = "hello :) :(";
var pattern = /:[()]/ig;
text = text.replace(pattern, function (match, p) {
    if (match == ':)') {
        return "happy";
    }
    else if (match == ':(') {
        return "sad";
    } else {
        return match;
    }
});
console.log(text);

演示:http://jsfiddle.net/JDx53/1/

如果你不想使用regex:

var happy_replacement = "smile!";
var sad_replacement = "frown...";
var happy_replaced = ":) Sunshine and lollipops".replace(":)",happy_replacement);
var sad_replaced = ":( Snips and snails".replace(":(",sad_replacement);
var both_replaced =
    ":( and :)"
        .replace(":(",sad_replacement)
        .replace(":)",happy_replacement);

编辑:一个同时做这两件事的函数。

function replace_all(raw) {
    var happy_replacement = "smile!";
    var sad_replacement = "frown...";
    var replaced =
        input
            .replace(":(",sad_replacement)
            .replace(":)",happy_replacement);
    return replaced;
}
var output = replace_all(":) and :(");