0

I'm checking the first character of a string for any non-alphanumeric characters from a multi-line textbox. If I pass in this string in, I get some hits.

ATest
BTest2
CAnother1
DThen some
2 More to go
FAny other some-day

Here's the javascript code:

function CheckFirstAlphaNum(textToTest, valueLabel, pattern, warningMessage)     
{
    var textValues = textToTest.split("\n");
    pattern = pattern || /([A-Za-z0-9]+)/gm;
    warningMessage = warningMessage || "The first character of a value in '" + valueLabel + "' has an invalid character. Please consider revising it."

    var goodText = true;
    for (var i = 0; i < textValues.length; ++i) {
        //alert(textValues[i]);
        var firstChar = textValues[i].substring(0, 1);
        if (!pattern.test(firstChar)) {
            alert(firstChar);
            alert(pattern);
            goodText = false;
        }
    }
    if (goodText != true) { alert(warningMessage); }
    return goodText;
}

Any ideas why? It fails on B, D, and F, so it seems like every other line.

M Kenyon II
  • 4,136
  • 4
  • 46
  • 94
  • It could be related line endings. Some systems use `\r\n` for the line ending, and if you are only splitting on `\n` you might have some troublesome whitespace in your strings. Try this `var firstChar = textValues[i].trim().substring(0, 1);` – Dan May 18 '15 at 18:33

3 Answers3

1

Probably because your regex is incorrect.

I'm not sure what the /gm switches at the end do, but try:

/^[A-Za-z0-9]/

From your original regex, a couple of points to note:

  1. ^ matches the start of the string
  2. + is not useful if you only care about a single character
Armand
  • 23,463
  • 20
  • 90
  • 119
1

The problem here is that you're using the g (global) modifier in your regex.

Run this code in your JS console to check that test() returns alternating true and false

r = /([A-Za-z0-9]+)/g
r.test('a')
> true
r.test('a')
> false
r.test('a')
> true
...

Removing the g modifier results in the regex always returning true for a string that matches. Since you're testing just one character using the multiline modifier m and the + (one or more matches) are unnecessary also.

Ezequiel Muns
  • 7,492
  • 33
  • 57
0

Your text most probably has Windows line breaks \r\n rather than only \n. So splitting at \n will result in \r entries on every other array index.

Those \r will "fire" the regex .test() method because it's not alphanumeric.

Try this

var textValues = textToTest.split("\r\n");
devnull69
  • 16,402
  • 8
  • 50
  • 61