Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

jquery - javascript regexp replace not working, but string replace works

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', '.')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

'/-[0-9]+x[0-9]+./i' is a string.

/-[0-9]+x[0-9]+./i is regex.

"hi".match('/hi/')  // returns null
"hi".match(/hi/)    // returns ["hi"]

Edit: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...