javascript regexp replace不起作用,但字符串替换有效 [英] javascript regexp replace not working, but string replace works
本文介绍了javascript regexp replace不起作用,但字符串替换有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jQuery,正在尝试编写模式替换,但是它不起作用.我有这个:
I'm working with jQuery and am trying to write a pattern replace, but it doesn't work. I have this:
var $featured_rewrite = $('#featured').not('.slideshow');
$featured_rewrite.children().attr('href', $featured_rewrite.find('img').attr('src').replace('/-[0-9]+x[0-9]+\./i', '.'));
我不明白为什么这样的事情起作用:
I don't understand why something like this works:
.replace('-500x277.', '.')
但是不是,我什至用工具检查了一下并确保它是有效的并且可以工作:
but not this, which I even checked with a tool and made sure it was valid and works:
.replace('/-[0-9]+x[0-9]+\./i', '.')
推荐答案
'/-[0-9] + x [0-9] + \ ./i'
是字符串.
/-[0-9] + x [0-9] + \ ./i
是正则表达式.
"hi".match('/hi/') // returns null
"hi".match(/hi/) // returns ["hi"]
另外,请注意,除了引号外,您的正则表达式没有其他问题.如果您需要替换多个匹配项,则可能要考虑使用/g
(即末尾的/gi
),仅此而已.
Also, just to be clear, there's nothing wrong with your regex other than the quotes. You may want to consider using /g
(i.e. /gi
at the end) if you need to replace more than one match, but that's it.
这篇关于javascript regexp replace不起作用,但字符串替换有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文