PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

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

 September 05, 2022     angularjs, javascript, jquery, removing-whitespace, trim     No comments   

Issue

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


Solution

  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



Answered By - byte is 8bits
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing