Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 593
urhen2000 Avatar asked Nov 18 '25 09:11

urhen2000


2 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);
like image 197
Eddie Avatar answered Nov 20 '25 00:11

Eddie


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);
like image 35
Robby Cornelissen Avatar answered Nov 20 '25 00:11

Robby Cornelissen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!