xiomai
xiomai

Reputation: 89

Javascript split result simplify

Is there a way to make this code more simplified?

<input type="text" id="tags" />

var splittext = document.getElementById('tags').value.split(' ');
if (document.getElementById('tags').value.split(' ').length < 2 || splittext[1] == '') {
   alert("Two tags required.");
}

is there another way to make

 splittext[1] == ''

be like

document.getElementById('tags').value.split(' ').something[1] 

to avoid using the line

var splittext = document.getElementById('tags').value.split(' ')

The purpose of this is when a user inputs one tag and made a space after it, the split detects 2 values which i would like to avoid the space being counted as another tag because that would be like, uhm, cheating.

Upvotes: 0

Views: 3765

Answers (4)

Royi Namir
Royi Namir

Reputation: 148524

yeah :

var g= document.getElementById('tags').value.split(/[ ]+/)

if (g.length==2)  // ok.....

http://jsbin.com/ovibef/edit#javascript,html

Upvotes: 0

faino
faino

Reputation: 3224

Something like this should do the trick:

var elem=document.getElementById('tags').value;
if(elem.indexOf(' ')>-1 && elem.split(' ').length>=2) {
    alert('Worked!');
} else if(!elem || elem.indexOf(' ')<0) {
    alert('Two tags required.');
}

Upvotes: 0

kitti
kitti

Reputation: 14814

Trim first, and split on any number of white space characters:

if (document.getElementById('tags').value.trim( ).split(/\s+/).length < 2) {
    alert("Two tags required.");
}

You will need to create the String.trim function if you want to support some versions of IE though... but it's a useful function to have. Put this in a utility js file, or just at the top of your js:

if(typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    }
}

Upvotes: 1

jzworkman
jzworkman

Reputation: 2703

You should change your code to this to avoid making multiple calls to the same dom element(you are splitting the same thing twice)

var splittext = document.getElementById('tags').value.split(' ');
if (splittext.length < 2 || splittext[1] == '') {
   alert("Two tags required.");
}

This is the whole point of using variables, to avoid calling the same function(with the same results) multiple times.

Upvotes: 0

Related Questions