使用 regex 的 javascript 正则表达式用多个 - 字符替换字符串
我目前有一串文本需要通过 jquery 进行修改。
> "space>space"
我目前有以下 jquery 来为我进行替换,
$('#breadcrumb').html($('#breadcrumb').html().replace(/&[^;]+;/g, ' - '));
我试图用单个 -
字符替换 >
,但是上面的正则表达式只是更改了输入字符串到 ---
而不是 -
任何帮助将不胜感激!
I currently have a string of text which needs to be modified via jquery.
> "space>space"
I currently have the following jquery to do the replacement for me
$('#breadcrumb').html($('#breadcrumb').html().replace(/&[^;]+;/g, ' - '));
I am trying to replace the >
with a single -
character, however the regex above is simply changing the enter string to ---
instead of -
Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为您的正则表达式:
正在寻找:
因此
和
>
都与该模式匹配。第二个 / 之后末尾的 g 表示进行全局替换 - 如果您将其保留,则只会替换第一个匹配项。您需要:
这会将
>
的所有实例更改为-
,同时忽略其他所有内容。如果您特别想仅在
>
被不间断空格包围的情况下替换它,有几种方法可以做到这一点,其中最简单的可能是:That's because your regular expression:
Is looking for:
So
and
>
both match the pattern. The g on the end after the second / means do a global replace - if you leave it off then only the first match will be replaced.You need:
This changes all instances of
>
to-
while ignoring everything else.If you specifically want to replace
>
only if it is surrounded by non-breaking spaces there are several ways to do it, the simplest of which is probably:您不是用
-
替换>
,而是替换以&
开头并以结尾的任何内容;
。如果只出现一次,则不需要
g
修饰符。You're not replacing
>
with-
, you're replacing anything that starts with&
and ends with;
.The
g
modifier isn't necessary if there's only one occurrence.