Skip to content Skip to sidebar Skip to footer

Checking Space Between Text In Javascript

I want to check the gap between two or more words, i have given as an input, in a text box. If there had any space, then i want to alert user that no space is allowing. I can check

Solution 1:

Just use the match() method of strings. For example:

'Spaces here'.match(' ');

That returns true.

'Nospace'.match(' ');

That returns false.

So for what you want, just use something like this:

if(cName.match(' ')){
   alert('Spaces found!');
   returnfalse;
}

Demo

Solution 2:

your question not very clear , but i hope you want to count your words you can use the following code to split a text and by using the length property you count the word

var b = document.getElementById("cName").value;
var temp = newArray();
    temp = b.split(' ');
var count= temp.length;

and if you want to validate your name field that should not use any space

if ( ^[A-Za-z]$.test(document.getElementById("cName").value) ) {
    // your code;
}

if ( document.getElementById("cName").value.indexOf(' ') > 0 ) {
    alert('space found');
}

Post a Comment for "Checking Space Between Text In Javascript"