Find characters in a string and add whole word to array when found

Viewed 131
var arr = [];
var str='This is mWORDy word docuWORDment';

if (str.indexOf('WORD') > -1) {
  arr.push(Whole word here)
}

This works but I need to push the whole words that contains WORD into the array.

So the result should be this:

arr['mWORDy','docuWORDment'];

How can I do this?

3 Answers

You can split the sentence and use filter to filter the array. Use includes to check if a string contains a certain word.

var str = 'This is mWORDy word docuWORDment';
var arr = str.split(" ").filter(o => o.includes("WORD"));

console.log(arr);

Using String.prototype.match() with a simple regular expression:

const str = 'This is mWORDy word docuWORDment';
const result = str.match(/\w*(WORD)\w*/g);

console.log(result);

You can use this regular expression to capture the matches in a group preceded and suffixed by word boundaries and push it into an array.

const pattern = /\b([A-Za-z]+WORD[A-Za-z]+)\b/gm;
const str = `This is mWORDy word docuWORDment`;
let m;

let matchedArr = [];

while ((m = pattern.exec(str)) !== null) {
  // Push the first captured group
  matchedArr.push(m[1]);
}

console.log(matchedArr);

Related