How to remove leading and trailing white spaces from input text?

I need to fix a bug in AngularJS application, which has many forms to submit data-

Every Text box in forms is accepting whitespaces(both leading and trailing) and saving them into the database. So in order to fix this I used ng-trim="true", it worked and data is getting saved correctly in the back-end.

Problem: Even after using ng-trim when I click on save/update, the form UI shows the text with white-spaces not the trimmed data. It shows correct data only when I refresh the page.

Can anyone guide me.. what will be the approach to fix this?

P.S. – I’m new to both JavaScript and Angular!

Thanks

Answer

  1. Using trim() method works fine, but is used in newer browsers.
    function removeWhitespaceUsingTrimMethod {
     
            var str = "    This is whitespace string for testing purpose     ";
            var wsr = str.trim();
            alert(wsr);
        }

Output: This is whitespace string for testing purpose

From Docs:

(method) String.trim(): string

Removes the leading and trailing white space and line terminator characters from a string.

  1. Using replace() method – works in all browsers

Syntax:

testStr.replace(rgExp, replaceText); str.replace(/^s+|s+$/g, ”);

function removeWhitespaceUsingReplaceMethod {
         
            var str = "    This is whitespace string for testing purpose     ";
            var wsr = str.replace(/^s+|s+$/g, '');
            alert( wsr);
    }

Output: This is whitespace string for testing purpose

Leave a Reply

Your email address will not be published. Required fields are marked *