Isak La Fleur Isak La Fleur - 23 days ago 13
Javascript Question

Why do String.prototype.match() return two elements when string only has one unique match?

I cant understand why this code snippet return an array on two strings "BEARING" instead of only a string "BEARING. Any ideas?



const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"

const noun = cleanedString.match(/\b(\w+)$/);
console.log(noun);




Answer Source

You need to use the global /g flag:

const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"

const noun = cleanedString.match(/\b(\w+)$/g);
console.log(noun);

From String.prototype.match() [MDN]:

If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec().