0

I need to check if current URL includes a few substrings. My code works but I need a tip if it possible to make it better. I realize that duplicating code is not a good practice. I am working with Angular 6/Typescript/ECMAScript 6.

const currentUrl = this.location.path();
const displayTile = currentUrl.includes('/search-resources') || currentUrl.includes('/calendar') || currentUrl.includes('/yearbooks')? 1 : 2;

2 Answers 2

2

Your code is just fine, if you want to reduce the length of checks, have the substrings in an array. like:

var substrings = ['/search-resources', '/calendar', '/yearbooks']

Test your condition using:

const displayTile = substrings.some((e) => currentUrl.includes(e)) ? 1 : 2

Array.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

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

1 Comment

@NataliaGurgul: Please consider accepting answers if they solve your question.
0

jQuery has $.inArray

var names = ['search-resources', 'calendar'];
if ($.inArray('calendar', names) !== -1) {
    // do stuff
}

2 Comments

I don't use jQuery
@NataliaGurgul you can check this link for your better answer frontstuff.io/…

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.