Replacing blank spaces in javascript

Hello! I need to catch if someone just tries to enter a space in a required field, and still give them "field is required " alert. I can’t get the script to work, instead of replacing only spaces, it replaces the entire string:

fld = document.getElementById('DM');
    var re =/\\s/g;
    RegExp.multiline = true; // IE support
    fld = (fld.value).replace(re,"");

Can someone please help? :shifty:thank you!

Try something similar to this.

This function checks for letters and spaces in a string. It also returns false if the string contains only spaces.

function isLettersAndSpaces(inpStr) {
    //test if inpStr is 0 length
    if(inpStr.length == 0)  return false;      //assume string is mandatory
    var foundNonSpace = false;
    //test if inpStr contains only letters or spaces
    var validChars = /[a-z A-Z]/;
    for(var i=0; i < inpStr.length; i=i+1) {
        if(inpStr.charAt(i) != " ") foundNonSpace = true;  
        if(!validChars.test(inpStr.charAt(i))) {
            return false;
    //at this point all characters have been checked
    return (foundNonSpace)? true : false;

If the function returns false you can give them your "field is required " or appropriate error message alert.

Thank you, but this still doesn’t work for me - it lets the empty string to be entered right through…

can you post your updated code because the line

if(inpStr.length == 0)  return false;

does not allow an empty string to get through.

Actually, I made my original code work. So here it is:

function trim (str) {
	var str2 = str;
	str2 = str2.value.replace(/^\\s+/, '');
	for (var i = str2.length - 1; i >= 0; i--) {
		if (/\\S/.test(str2.charAt(i))) {
			str = str2.substring(0, i + 1);
	return str2;