theglossy1
theglossy1

Reputation: 553

JavaScript regex does opposite of what's expected

I have a regex that's doing the opposite of what's expected... I have something that could either be a number or not. I tried using isNaN but it gave odd results, so I thought I'd try a regex. That is giving even weirder results. The html looks like <span class="label">31</span> and I grab it via var text = document.querySelectorAll('.label, .content');

Then I process it via:

for (var i=0; i<text.length; i++) {
 if (text[i].innerText.search(/^[0-9]+$/)) {
  // do number stuff
 }
}

but it matches everything that's not a number and doesn't process the numbers. If I change the regex to /^[^0-9]+$/ (the negating character) it does match on the numbers. This is the opposite of what I would expect! Anybody have an idea what might be going on?

Thanks.

Upvotes: 1

Views: 106

Answers (4)

suraj
suraj

Reputation: 53

remove that "^" and try. because "^" requests to select items that doesn't match the regex expression. so it should be /[0-9]+$/ not /^[0-9]+$/.

Upvotes: 0

sherb
sherb

Reputation: 6095

If all you're going to do is check for the presence of a match, use test:

if(/^[0-9]+$/.test(text[0].innerText)) {
    ...
} 

Upvotes: 0

Bergi
Bergi

Reputation: 664307

The search method works like indexOf and returns the index where the regex has been found, or -1 if it was not found. As your regex would only match at position 0, it returns only that or -1 - and while -1 is a truthy value, 0 is not. That's why the behaviour is "inverted".

You could do

if (text[i].innerText.search(/^[0-9]+$/) == 0) 

but you'd better use the test method of the regex object which returns the boolean that you want:

if (/^[0-9]+$/.test(text[i].innerText)) 

Upvotes: 3

Michael Mikhjian
Michael Mikhjian

Reputation: 2794

Don't use search, use match.

var text = document.querySelectorAll('.label');

if( text[0].innerText.match(/^[0-9]+$/) ){
 console.log("Has numbers")
}else{
 console.log("No numbers")
}
<span class="label">31</span> 

Upvotes: 1

Related Questions