Skip to content Skip to sidebar Skip to footer

Why This String.search Doesn't Work As Expected?

Why this returns a 0 as expected 'https://www.site.com/abc?sk=1'.search('https://www.site.com/abc?') But this returns a -1 as 0 is expected? 'https://www.site.com/abc?sk=1'.search(

Solution 1:

because the ? has a special meaning in regular expressions.

Use indexOf instead (which works with plain strings) when you don't need regular expressions:

'https://www.site.com/abc?sk=1'.indexOf('https://www.site.com/abc?sk')

Solution 2:

<script>if('https://www.site.com/abc?sk=1'.indexOf('https://www.site.com/abc?sk')>=0){ 
   //Do something you want
}
</script>

Post a Comment for "Why This String.search Doesn't Work As Expected?"