Make if condition with split

Asked

Viewed 263 times

3

I need to make a condition, where I check on a input the user entered the character ..

So I’m making one if where I do split with my input value.

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

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

Fiddle here

There is another way to make the condition?

  • Where do you get idCliente can put this code?

1 answer

7


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

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

That is, check if the split generates an array with more than one element.


Example of a 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

  • 1

    That’s right. I was checking for data in [1] of my array. Hence my error. Thanks @Sergio

Browser other questions tagged

You are not signed in. Login or sign up in order to post.