0

我刚刚看到以下帖子使用正则表达式 c# 将表情符号替换为推文中的单词,其中笑脸被解析并替换为一些自定义文本:

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# 中所做的相同行为?

4

3 回答 3

0

您可以使用“替换”方法的重载:

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/

于 2013-06-10T21:28:01.127 回答
0
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"
于 2013-06-10T21:05:29.793 回答
0

如果你不喜欢使用正则表达式,这样的事情:

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 :(");
于 2013-06-10T21:14:09.853 回答