hi,

please i want to make function java script that check if user enter empty string((" ") more one space) or no if yes prevent this string from submit to database (this string will enter to database)

i know there are function trim() can remove empty string from text but not work with me .

Recommended Answers

All 5 Replies

javascript doesn't have a native trim function, however this way does work

var trimmed = str.replace(/^\s+|\s+$/g, '');

hi
please can you explain this syntax str.replace(/^\s+|\s+$/g, '')

Str is you string variable, a string is an object with a number of properties and methods, one of which is replace. The messy looking first parameter to replace is a regular expression in javascript which in essence looks for spaces both at the start and end of the string but not in the middle. The second parameter ('') is the value to replace the found characters with. Hence we are replaceing all the found spaces at the start and end with blank strings, thus deleting them from the string.

Look up "regular expressions" to understand this.

Better yet, add a new function to the String object type by using the prototype property.

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

And then use the function trim as if it belonged to the String type.

var str = "   okay this works fine    ";
alert(str.trim());
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.