Reputation: 187
i want to know the best way to check if a string contains a subString or part from subString in typeScript ?
for example i have a string path : "home/jobs/AddJobs" And i want to check if it's equal or it contains : "home/jobs"
how can i do that in Angular 6 typescript ?
Upvotes: 7
Views: 20010
Reputation: 251082
There is a traditional and modern answer to this question:
const path = 'home/jobs/AddJobs';
// Traditional
if (path.indexOf('home/jobs') > -1) {
console.log('It contains the substring!');
}
// Modern
if (path.includes('home/jobs')) {
console.log('It includes the substring!');
}
string.prototype.includes
is available in ECMAScript 2015 and newer. If you target lower versions, indexOf
works or you can use the MDN Polyfill.
includes
is functionally the same as indexOf
but naturally returns a boolean
value, so you don't need to write the > -1
condition.
Upvotes: 19