How do I trim a string in javascript?
Edit
A bug has been spotted in the javascript code. The cause was extra spaces inside a CSV value ("123, 456 , 789"), for which we were doing split(',') . I was thinking the core JS String object will have the trim function, but turns out there is no native one. Then with the help of my good friend (google), I found some implementation of doing it
1. extend the String object in JS so that you can just do myString.trim(); You can get the implementation here How do I trim a string in javascript?
2. use the jQuery build in $.trim() which was there since jQuery 1.0 , syntax $.trim(myString); user manual : http://api.jquery.com/jQuery.trim/
3. use regex to remove all space inside the string . e.g. myString.replace(/[^0-9-.,]/g, ''); so only number , hypen, period and comma is allowed in "myString"
For my case I put the #3, as I can do a global remove before doing the split to save a for loop. i.e.
var Arr = myCsvString.replace(/[^0-9-.,]/g, '').split(',');
1. extend the String object in JS so that you can just do myString.trim(); You can get the implementation here How do I trim a string in javascript?
2. use the jQuery build in $.trim() which was there since jQuery 1.0 , syntax $.trim(myString); user manual : http://api.jquery.com/jQuery.trim/
3. use regex to remove all space inside the string . e.g. myString.replace(/[^0-9-.,]/g, ''); so only number , hypen, period and comma is allowed in "myString"
For my case I put the #3, as I can do a global remove before doing the split to save a for loop. i.e.
var Arr = myCsvString.replace(/[^0-9-.,]/g, '').split(',');
How do I trim a string in javascript?
Reviewed by DF
on
7:08:00 PM
Rating: