Natalia Gurgul
Natalia Gurgul

Reputation: 79

How to check if string (current URL) includes a few substrings

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;

Upvotes: 0

Views: 787

Answers (2)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

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.

Upvotes: 2

Abdul Basit
Abdul Basit

Reputation: 1382

jQuery has $.inArray

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

Upvotes: 0

Related Questions