Javascript regexp replace doesn't work, but string replaces work

I am working with jQuery and trying to write a template replacement, but this will not work. I have it:

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 that I even checked with the tool and made sure that it is valid and works:

 .replace('/-[0-9]+x[0-9]+\./i', '.') 
+6
source share
1 answer

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

/-[0-9]+x[0-9]+\./i is a regular expression.

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

Edit: Also, to be clear, there is nothing wrong with your regular expression other than quotation marks. You might consider using /g (i.e. /gi at the end) if you need to replace a few matches, but that is.

+35
source

Source: https://habr.com/ru/post/892466/


All Articles