我刚刚看到以下帖子Replace emoticon with word in tweet using regex 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#中所做的相同行为?
答案 0 :(得分:0)
var result = "hello :)".replace(/:[()]/, "replacement");
有关详细信息,请参阅JavaScript string replacement method。
在你的情况下,我可能不会使用正则表达式。我会这样做 -
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"
答案 1 :(得分: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 :(");
答案 2 :(得分: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);