Programming in Java and PHP has given me the impression that the trim() method which can be found in the aforementioned languages will be present in most popular languages. To my dismay, I looked hard for that function in the String class while doing some JavaScript coding recently. Luckily enough I did eventually stumble upon the regular expression that would help to trim leading spaces as well as trailing spaces in a string. It's as follows:
var s = " Adobe Flex is a good technology for implementing RIAs ";
//To remove leading spaces, i.e.spaces before the string s, use
s = s.replace( /^\s+/g,'');
//To remove trailing spaces, i.e.spaces after the string s, use
s = s.replace( /\s+$/g,'');
//To remove both spaces(i.e.both leading and trailing), use
s = s.replace( /^\s+/g,'').replace(/\s+$/g,'');
You never know, it might come in handy someday.
No comments:
Post a Comment