简体   繁体   English

用正则表达式中的字符替换字符串

[英]Replace string with Characters in Regex

I need to replace this string:我需要替换这个字符串:

var img = "<img class='messages-emoji' src='js/message/emoji/thumbsup.gif'>" ;

with this:有了这个:

(smile) (微笑)

Here's what I tried:这是我尝试过的:

var new = img.replace("<img class='messages-emoji' src='js/message/emoji/thumbsup.gif'>", "(smile)");

I need to replace this in Regex Javascript我需要在Regex Javascript 中替换它

I think the issue is that you are using the reserved word new as your variable name.我认为问题在于您使用保留字new作为变量名。 I suggest changing to something different:我建议改变一些不同的东西:

 var newImg = img.replace("<img class='messages-emoji' src='js/message/emoji/thumbsup.gif'>", "(smile)");

As others have pointed out, regex doesn't make sense for this use case, a simple string replace is better for multiple reasons.正如其他人指出的那样,正则表达式对于这个用例没有意义,出于多种原因,简单的字符串替换更好。

Regex would generally be used when you want to replace a string with variable parts, but you know some (pattern) of the source string.当您想用可变部分替换字符串时,通常会使用正则表达式,但您知道源字符串的某些(模式)。 An example in your case would be if the src attribute could be anything, but you knew the tag was always going to have the messages-emoji class (Though even in this case, there are better ways to achieve this).在你的例子中,如果src属性可以是任何东西,但你知道标签总是会有messages-emoji类(尽管即使在这种情况下,也有更好的方法来实现这一点)。

That said, I'll keep my answer in place as it does seem to have solved your problem.也就是说,我会保留我的答案,因为它似乎确实解决了您的问题。


There a number of things wrong here:这里有很多错误:

  • The new keyword is a reserved word in JavaScript, you need to choose a different name for your variable here otherwise you will get a syntax error. new关键字是 JavaScript 中的保留字,您需要在此处为​​变量选择不同的名称,否则会出现语法错误。
  • Your string contains / characters, which is used to denote a literal regular expression in JavaScript.您的字符串包含/字符,用于表示 JavaScript 中的文字正则表达式。 You need to escape each of these with the \\ character.您需要使用\\字符对其中的每一个进行转义。
var img = "<img class='messages-emoji' src='js/message/emoji/thumbsup.gif'>";
var regex = /<img class='messages-emoji' src='js\/message\/emoji\/thumbsup.gif'>/;

var newImg = img.replace(regex, "(smile)");

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

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