0

I have a variable like,

var url = "/login/user"; 

And I have an array like,

var x = ["login", "resetpassword", "authenticate"]; 

Now I need to check, whether that url string is present in an array of string. As we can see that login is present in an array but when i do x.indexOf(url), it always receive false because the field url has rest other letters also. So now how can I ingnore those letters while checking a string in an array and return true?

0

3 Answers 3

2

Use .some over the array instead:

var url = "/login/user"; var x = ["login", "resetpassword", "authenticate"]; if (x.some(str => url.includes(str))) { console.log('something in X is included in URL'); }

Or, if the substring you're looking for is always between the first two slashes in the url variable, then extract that substring first, and use .includes:

var url = "/login/user"; var x = ["login", "resetpassword", "authenticate"]; var foundStr = url.split('/')[1]; if (x.includes(foundStr)) { console.log('something in X is included in URL'); }

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

1 Comment

2

One way is to split url with / character and than use some

var url = "/login/user"; var x = ["login", "resetpassword", "authenticate"]; let urlSplitted = url.split('/') let op = urlSplitted.some(e=> x.includes(e)) console.log(op)

1 Comment

2

You could join the given words with a pipe (as or operator in regex), generate a regular expression and test against the string.

This works as long as you do not have some characters with special meanings.

var url = "/login/user", x = ["login", "resetpassword", "authenticate"]; console.log(new RegExp(x.join('|')).test(url));

4 Comments

resulting in /login|resetpassword|authenticate/.test("/login/user") - clever
Note: It will return true on authenticate in "/logged/authenticateduser"
as the other solutions.
Sure. But yours seemed the cleverest. Dupe of this though stackoverflow.com/a/5582621/295783

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.