Link to home
Start Free TrialLog in
Avatar of itnifl
itniflFlag for Norway

asked on

JavaScript string.match(pattern) return first match twice along with plenty of undefined

I send the regex to a function as a string validatorRegExp.
In the function the code tests the contents of another string nametxt with the received regular expression string validatorRegExp as so:
if (nametxt.match("/"+validatorRegExp+"/g")) { }

validatorRegExp contains the following regex:
(^\.)|(\()|(\))|(;)|(:)|(")|(<)|(>)|(\*)|(\+)|(=)|(\\)|(\/)|(\|)|(\?)|(,)|(\$)|(\#)|(\^)|(\[)|(\])|(\.$)|(\!)|(%)|(\&)|(\{)|(\})|(\~)|(`)|(¨)

When testing the regex at http://regex.larsolavtorvik.com/ it behaves as it should, returning all the matched caracters in an array.

However, this JavaScript tested in Chrome returns the first match from nametxt twice, and then a bunch of undefined. As so:
["&", undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "&", undefined, undefined, undefined, undefined, undefined]

Whats up with that? I don't want all those undefined values. I want all matched charadters in an array.
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

I'm pretty sure that pattern isn't actually doing what you want (or expect) it to. Can you please explain what you want the pattern to achieve, and I'll review it for you.

Note that I understand you want the matched characters in an array. Which characters should or shouldn't be at the start or end of the string though?
ASKER CERTIFIED SOLUTION
Avatar of itnifl
itnifl
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I don't wish to object to this question being closed with the provided reason; however I am here to help, and would be more than happy to adjust my regex for you if it's not matching the full string you require. Simply provide the full string not being matched, the line of code containing your regex, and the portion of the string that *is* being matched, and I'll see if I can't fix the problem poste haste. :-)
Avatar of itnifl

ASKER

Your answer is being set as part of the answer, so you will get the full 500 points. I can't reward points to my self. I am choosing my answer as a part of the total answer to highlight it for easier lookups later, and for other users who might google this or find it otherwise.
Avatar of itnifl

ASKER

Partially selectec my answer as an solution to highlight it as a part of the answer.