callmesingham
callmesingham

Reputation: 3

Why is a regex matched string behaving oddly?

I have a piece of code as shown below :

    let regex = /^[^aeiou]+(?=[aeiou])/;
    let regexStr = "hhhhello".match(regex);
    console.log(regexStr.length); // prints 1

Shouldn't it print 4? However if I add a "" to regexStr, it shows the right value.

    let regex = /^[^aeiou]+(?=[aeiou])/;
    let regexStr = "hhhhello".match(regex) + "";
    console.log(regexStr.length); // prints 4

Can someone explain what's happening?

Upvotes: 0

Views: 37

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

The /^[^aeiou]+(?=[aeiou])/ regex only matches a single chunk of 1+ chars other than a, e, i, o, u that are followed with a a, e, i, o or u letters, at the start of string.

You may use

let regex = /[^aeiou](?=[^aeiou]*[aeiou])/gy; 
let regexStr = "hhhhello".match(regex);
console.log(regexStr.length); // prints 4, regexStr = ["h", "h", "h", "h"]

The /[^aeiou](?=[^aeiou]*[aeiou])/gy matches only from the start of string thanks to the y sticky modifier, while g will make it match multiple times till the first failure.

  • [^aeiou] - matches 1 char other than a, e, i, o and u
  • (?=[^aeiou]*[aeiou]) - if it is immediately followed with any 0 or more occurrences of these chars followed with 1 letter, a, e, i, o or u.

See the regex demo.

Upvotes: 0

AimusSage
AimusSage

Reputation: 756

Because string.match() actually returns an array of all matched values. In your case, it is only 1.

When you add the "" it is instead converted into a string value.

For more info you can check these docs on string.match()

Upvotes: 1

oriberu
oriberu

Reputation: 1216

In your example, regexStr is an array with one element, the string hhhh. By adding a string you implicitly convert to string, which then has length 4. You could just use regexStr[0].length.

Upvotes: 1

Related Questions