1

Now I have a URL which is

var url1 = 'www.test.com/test'

If I use

url1.indexOf('/test') !== -1  // will return true

What if I change the URL to

var url2 = 'www.test.com/test123'
url2.indexOf('/test') !== -1. // still return true

What I want to do is only this pattern /test can return true otherwise return false, for example /test123 or /test12312

2
  • 1
    What do you expect from www.test.com/test/1234 or www.test.com/abc/test. And that’s not really a URL btw. Commented Apr 11, 2018 at 6:10
  • var hasTest = url1.split("/").slice(1).some( s => s == "test" ); Commented Apr 11, 2018 at 6:13

3 Answers 3

5

You can use .endsWith() method of String:

let url1 = 'www.test.com/test',
    url2 = 'www.test.com/test123';

console.log(url1.endsWith('/test'));
console.log(url2.endsWith('/test'));

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

Comments

0

guess you want this:

var url1 = 'www.test.com/test';
var url2 = 'www.test.com/test123';
let reg=/\/test$/;
console.log(!!url1.match(reg));
console.log(!!url2.match(reg));

1 Comment

@Dreams,if it works,you can close the question by voting up or accepting the answer
0

If you want to check if the URL contains /test anywhere in the URL path after origin then use split, slice and some

var fnHasValue = (url1, valueToCheck) => url1.split("/").slice(1).some( s => s === valueToCheck );

This should work for

fnHasValue("www.test.com/test", "test" ) //true
fnHasValue("www.test.com/test123", "test" ) //false
fnHasValue("www.test.com/abc/test", "test" ) //true
fnHasValue("www.test.com/test/abc", "test" ) //true

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.