Home > OS >  how to print all values from an array containing a given string value (JavaScript)
how to print all values from an array containing a given string value (JavaScript)

Time:08-09

Given an array like the below code :

let words = ['bring','constant','bath','spring','splashing']

How do I print all string characters with ing characters from the words array ?

CodePudding user response:

You need to use endsWith method to check if the word ends with a specific value.

let words = ['bring','constant','bath','spring','splashing']

const result = words.filter(w => w.endsWith('ing'))

result.forEach(w => console.log(w))

You also can use regular expressions with dollar sign $ means end with.

let words = ['bring','constant','bath','spring','splashing']

const result = words.filter(w => /(ing)$/.test(w))

result.forEach(w => console.log(w))

CodePudding user response:

As author want to check if ing exist in the middle of the word or not. In that case you can just use normal regex with String.match() method without $ sign at end.

Live Demo :

let words = ['bring','constant','bath','spring','splashing', 'tingtong'];

const res = words.filter(word => word.match(/ing/ig));

console.log(res);

Or you can also achieve that by using .includes() method.

Live Demo :

let words = ['bring','constant','bath','spring','splashing', 'tingtong'];

const res = words.filter(word => word.includes('ing'));

console.log(res);

  • Related