0

I am trying to match this url:

https://play.spotify.com/user/randomuser/playlist/71ljVu3Ejccu2PzW6iXv0G

where random user and the ending id are changing.

I want to verify that the url is indeed a play.spotify.com link and matches that format.

I have this javascript function:

var verify = function(url){
    var re = new RegExp("(https:\/\/play.spotify.com\/user\/\w+?\/playlist\/\w+)", "g");
    var result = re.exec(url);
    console.log(result);
}

verify("https://play.spotify.com/user/useruser/playlist/71ljVu3Ejccu2PzW6iXv0G");

When I tested it out using a regex tester, it seems to work correctly:

enter image description here

The output of the console.log, however, is just null.

What am I doing wrong in the javascript? Why isn't the url properly matching?

2

2 Answers 2

5
"(https:\/\/play.spotify.com\/user\/\w+?\/playlist\/\w+)"

You're escaping the characters / and w here, which is not necessary in a string literal. Your string is equivalent to

"(https://play.spotify.com/user/w+?/playlist/w+)"

which obviously now is not the regex that you're looking for.

Don't use the RegExp constructor, use a regex literal:

var re = /(https:\/\/play.spotify.com\/user\/\w+?\/playlist\/\w+)/g;

If you really needed to use new RegExp for some reason, you'd have to escape the backslash character in your string: new RegExp("(https://play.spotify.com/user/\\w+?/playlist/\\w+)", "g").

Sign up to request clarification or add additional context in comments.

1 Comment

In that last regex you forgot to escape the first \w+? as well.
1

You don't need to use the RegExp constructor, and can use the string.match(regex) function to get the result:

var verify = function(url) {
  var regex = /https:\/\/play.spotify.com\/user\/\w+?\/playlist\/\w+/g;
  var result = url.match(regex);
  console.log(result);
};

// Passes, logs the URL:
verify("https://play.spotify.com/user/useruser/playlist/71ljVu3Ejccu2PzW6iXv0G");

// Fails, logs null
verify("https://play.spotify.com/useruser/playlist/71ljVu3Ejccu2PzW6iXv0G");

See jsBin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.