stack
stack

Reputation: 10218

How to implement any-digit in the condition?

I'm trying to detect string is list-item-style or not ..., Also I have this code:

var test = "1. anything";
if( test[0] == /\d/ && test[1] == '.' ) { alert("it is list-item") }

But I never see a alert(). Why? I expect to see that alert because first character of that variable is a digit and second character is ..

Upvotes: 0

Views: 44

Answers (3)

Venkat.R
Venkat.R

Reputation: 7736

Try like this below with working demo !

Solution 1: with test function

var test = "1. anything";
if( /\d/.test(test[0]) && test[1] == '.' ) { alert("it is list-item") }

Solution 2 with Number Class

    var test = "1. anything";
    if( test[0] == Number(test[0]) && test[1] == '.' ) { alert("it is list-item") }

Upvotes: 1

dikesh
dikesh

Reputation: 3125

How about this

if (test.match(/^\d+\.*/) !== null) {
    alert('it is list-item');
}

Upvotes: 2

tanenbring
tanenbring

Reputation: 780

You are not using regular expressions correctly. You can't just check if a string equals a regular expression, you need to call a method either on the string or on the regular expression.

var test = "1. anything";
if( /\d/.test(test[0]) && test[1] == '.' ) { alert("it is list-item") }

Notice that I am using the RegExp function "test".

Using regular expressions correctly, you can reduce this conditional to:

if( /^\d\./.test(test) ) {
   alert("it is list-item");
}

Upvotes: 1

Related Questions