7

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 ?

1
  • Is there a code that shows what you have tried by any chance ? Commented Nov 28, 2018 at 13:44

1 Answer 1

19

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.