Searching strings

Kim Massaro
30-12-2017

This will be a short post, but hopefully it will come in handy if you’re not aware of the new methods provided in ES6 to search through strings easier. I’ll show you a few of them in the examples below. You can also see per example how you could do it with a regular expression.

startsWith

To check if a string begins with a particular set of characters, you can use the startsWith method.

let quote = 'There are two ways to write error-free programs; only the third one works.';

console.log(quote.startsWith('There'));

// Possible to give a parameter with the position you want to start indexing
console.log(quote.startsWith('There', 2));

// Example regular expression
console.log(/^There/.test(quote));

endsWith

To check if a string ends with a particular set of characters, you can use the endsWidth method.

let quote = 'A good way to stay flexible is to write less code';

console.log(quote.endsWith('code'));

// Possible to give a parameter to indicate the maximum characters to search through
console.log(quote.endsWith('code', 10));

// Example regular expression
console.log(/code$/.test(quote));

includes

To check if a string includes a word, you can use the includes method.

let quote = 'Are you ready to level up? Want to grow? Join us at Competa!';

console.log(quote.includes('grow'));

// Example regular expression
console.log(/grow/.test(quote));

LEAVE A REPLY

you might also like