0

I didn't see any related messages that directly answer this question so I'll post below.

I noticed that the regex.test() function in JavaScript does not behave the same as "matches" in Java.

function doit(string)
{
    var finalString = "";  // our result at the end.
    var stringArray = string.split(/\s+/);
    var arrayIndex = 0;
    let regexp = /[A-Z]+/
    // use shortcut evaluation (&&)
    while (arrayIndex < stringArray.length && regexp.test(stringArray[arrayIndex]) )
    {
        finalString += stringArray[arrayIndex] + " ";
        arrayIndex++;
    } // end while
    return finalString
}

If I call "doit()" with "Hello World", the functions returns: "Hello World". Huh?

How is that possible with my [A-Z]+ regular expression?

The regular expression [A-Z]+ in Java means capital letters only and works as expected. In Java, nothing would be returned.

Java: stringArray[arrayIndex].matches("[A-Z]+") // returns nothing as expected.


So, I'm a bit confused about how to match a regex in JavaScript.

Thanks in advance for helping clarify this for me. :)

Ivar
  • 6,138
  • 12
  • 49
  • 61
Morkus
  • 517
  • 7
  • 21

1 Answers1

0

The regex should be

let regexp = /^[A-Z]+$/

This way you tell js to match these characters when the line starts and then ends. The way you have it, it matches just the first letter, so the test returns true.

d3bgger
  • 339
  • 2
  • 12
  • Thanks very much. Being new to JavaScript after 20 yrs in Java, I didn't understand the anchor requirement. – Morkus May 10 '20 at 19:11