String.replace()不起作用,即使在其他语言中使用相同的regex

String.replace() not working, even though the same regex does in other langs?

本文关键字:语言 regex 其他 replace 不起作用 String      更新时间:2023-09-26

我有一个textarea元素,它包含以下形式的文本:

 215
 00:10:38,810 --> 00:10:40,040
 [ROBIN LAUGHING]
 216
 00:10:40,370 --> 00:10:41,330
 [ALL SCREAMING]

我获取该文本并对其运行replace(/^['d's-:,>]+$/g, '');,然后console.log结果。但我看到的是不变的结果,而不是任何变化。

我使用Ruby的String#gsub方法在同一文本上尝试了相同的regex,它完全符合我的要求。我有点困惑JavaScript的不同之处。

尝试使用此regexp /^['d's'-:,>]+$/mg,而不是您使用的regexp。

另外,请记住.replace将保持原始字符串不变,因此您应该执行以下操作:

myString = myString.replace(/^['d's'-:,>]+$/mg, "");