简体   繁体   English

使用正则表达式的javascript正则表达式用多个字符替换字符串

[英]javascript regular expressions using regex is replacing the string with multiple - characters

I currently have a string of text which needs to be modified via jquery. 我目前有一串需要通过jquery修改的文本。

 >    "space>space"

I currently have the following jquery to do the replacement for me 我目前有以下jquery为我做替换

$('#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! 任何帮助将不胜感激!

That's because your regular expression: 那是因为你的正则表达式:

/&[^;]+;/g

Is looking for: 在寻找:

&      an ampersand, followed by
[^;]+  one or more characters that are not semicolons, followed by
;      a semicolon

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. 第二个/表示结尾后的g进行全局替换 - 如果你关闭它,那么只会替换第一个匹配。

You need: 你需要:

.replace(/>/g, '-')

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: 只有当它被不间断的空间包围时,有几种方法可以做到,最简单的方法可能是:

.replace(/ > /g, ' - ')
replace(/>/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. 如果只有一次出现,则不需要g修饰符。

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

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