Make condition if with split

3

I need to make a condition, where I check if a input has entered the character . .

For this I am doing a if where I make split with value of my input.

if (idCliente.split('.')[1].length > 0)

If input has . everything works fine, but if there is no javascript error in .length (says it is undifined) and does not run the rest of the function.

Fiddle here

Is there another way to do this?

    
asked by anonymous 11.04.2014 / 11:33

1 answer

7

If the split finds a . then you want to measure the length of idCliente , not the string length of the second element of the possible array. Try this:

idCliente.split('.').length > 1

That is, to see if split generates an array with more than one element.

Example code:

var stringA = 'abcde';
var stringB = 'abc.defgh';

console.log(stringA.split('.').length); // 1 (array)
console.log(stringB.split('.').length); // 2 (array)
console.log(stringB.split('.')[1].length); // dá 5, porque está a medir a string

jsFiddle

    
11.04.2014 / 11:35