user3350731
user3350731

Reputation: 972

Regex match in jQuery

I'm having kind of trouble match all the url that has the same format like this : planning|test/test and if so, to store in LocalStorage. Here's my code :

if( window.location.href.split('#')[1].match('/planning\|[a-z]*\/[a-z]*/'))
{
    localStorage.setItem('hash_tag', window.location.href.split('#')[1]);
}

The issue here is the regex match doesn't quite do the job here. Any help with this? Much appreciated.

Upvotes: 1

Views: 137

Answers (2)

a1111exe
a1111exe

Reputation: 641

Don't use "'" (apostrophes) symbols for regex pattern in match. Try to run the following 2 samples in your browser's console (I checked in FF 39):

// prints 'MATCH'
var to_match = 'planning|test/test';
if (to_match.match(/planning\|[a-z]*\/[a-z]*/)) {
    console.log('MATCH');
} else {
    console.log('WAT');
}

// prints 'WAT'
var to_match = 'planning|test/test';
if (to_match.match('/planning\|[a-z]*\/[a-z]*/')) {
    console.log('MATCH');
} else {
    console.log('WAT');
}

Also, you may use https://regex101.com/#javascript to test your regexes.

Good luck!

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

The main issue with your regex is that you declared it with '...'. You need to remove ' around the regex string literal.

In case the strings can have both planning OR [a-z]*/[a-z]*, you can use

if( window.location.href.split('#')[1].match(/planning|[a-z]*\/[a-z]*/)) {
      localStorage.setItem('hash_tag', window.location.href.split('#')[1]);
}

or

if( /planning|[a-z]*\/[a-z]*/.test(window.location.href.split('#')[1])) {
      localStorage.setItem('hash_tag', window.location.href.split('#')[1]);
}

Note that \| matches a literal | symbol and does not denote alternation.

If you want to match | as a literal, just use

if( /planning\|[a-z]*\/[a-z]*/.test(window.location.href.split('#')[1])) {
      localStorage.setItem('hash_tag', window.location.href.split('#')[1]);
}

Upvotes: 1

Related Questions