Tips Week 2.1 - JavaScript Trim() Function
I'm going to be too busy this week to blog anything insightful, so I'll do another tips week. Starting today with a little extension to the JavaScript String object.
Add this function to a JS library somewhere:
String.prototype.trim = function() { a = this.replace(/^\s+/, ''); return a.replace(/\s+$/, ''); };
Then you can call is from wherever you like, as so:
alert(" test" + " this ".trim() )
The result of which is a prompt showing " test this". Or use like this:
<input type="test" onchange="this.value=this.value.trim()" >
It's a useful function. Don't leave home without it.
More String extensions here. More tips each day this week.
Ummm. Is that a typo? Surely the alert above should return " testthis".
You could shorten this to something like;
return this.replace(/^\s*(\b.*\b|)\s*$/, '');
which will remove leading/trailing whitespaces. But does anybody have anything which will act like @Trim and cut out whitespaces in the middle of strings?
Woops. Yes. It is and it will.
Ah. Here we go. A Regexp which will remove repeated whitespaces and replace with a single space.
return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
Not perfect (turns tabs into spaces) but close enough for me.
Trim is always useful. That's why I have these:
String.prototype.trim = function() {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}
String.prototype.fulltrim = function() {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");
}
Not sure whether they bring anything else to the party. But I have been using them for a long while and hand no complaints, yet.
A couple other handy ones include:
String.prototype.right = function(count) {
return this.substr(this.length - count);
}
String.prototype.left = function(count) {
return this.substr(0, count);
}
Duplicating Lotusscript/@Formula functions in Javascript is frequently useful, I have found the @Unique(list) capability especiually so.
here is a JS version :
Array.prototype.indexOf = function(str,ignoreCase) {
// return the index of the first instance of str in the array
// else -1 if not a member
// if a string array can take a flag to request case match
// if (ignoreCase) then 'StringA' is considered the same as 'sTrinGa'
var tmp ;
if (typeof(str)=="string" && ignoreCase) {
str = str.toLowerCase() ;
}
for (var i=0; i<this.length; i++) {
if (typeof(str)=="string" && ignoreCase) {
tmp=this[i].toLowerCase() ;
} else {
tmp=this[i] ;
}
if (tmp==str) return i ;
}
return -1 ;
}
Array.prototype.isMember = function(str,ignoreCase) {
return this.indexOf(str,ignoreCase) > -1 ;
}
Array.prototype.unique = function(ignoreCase) {
// creates a unique array
// empty arrays are always unique !
if (this.length==0) return this ;
// default to respect case
// if (ignoreCase) then 'StringA' is considered the same as 'sTrinGa'
if (arguments.length==0) ignoreCase = false ;
var newList = new Array(this[0]) ;
var found,tmp1,tmp2 ;
for (var i=0; i<this.length; i++) {
if (!newList.isMember(this[i],ignoreCase)) newList.push(this[i]) ;
}
return newList ;
}
To be really bulletproof you may want to check that the browser supports array.push() and if not then implement one !
Regards
Ron Yuen
Hi Jake et al,
Anyone know how 'fully' @Trim an html textarea?
e.g. create an editable text field with, say 5 rows and 20 cols, and allow multiple values. Then populate the text area with just spaces and carriage returns.
If you put @Trim(@ThisValue) in the Input Translation and submit the form then all the 'whitespace' is removed, but there doesn't seem to be a way to do this in javascript prior to submitting the form...
Any ideas anyone?!
//*** removes whitespace fom begining and end of a string and returns it to whereever.
function trim(string){
if(string.indexOf(" ") == 0){
while(string.indexOf(" ") < 1){
string = string.substring(1,string.length) ;
}
}
if(string.substring(string.length-1,string.length) == " "){
while(string.substring(string.length-1,string.length) == " "){
string = string.substring(0,string.length-1) ;
}
}
return string;
}
function yourFunction(str){
....
str = trim(str);
....
}
Thank you very much.
This little func was just what i was looking for.
Keep it up !
Robert's code is flawed. If the string has leading spaces but no trailing spaces then it will get caught in an infinite loop.
Here's a version that will allow for leading spaces only, trailing spaces only, both leading and trailing spaces and no leading or trailing spaces.
function trim(string){
' remove leading spaces
while(string.substr(0,1)==" ")
string = string.substring(1,string.length) ;
' remove trailing spaces
while(string.substr(string.length-1,1)==" ")
string = string.substring(0,string.length-2) ;
return string;
}
I need the following output:
I have a variable in which the value it has is:
" 1 : 3300"
I need to trim it to 3300 and store it as an integer.
How is it possible?
Please do reply.
Thank you,
Regards,
Sowmya,
Bangalore, India
There are many required functions which are not available in Native JavaScript.Get trim and more functions like trim() for JavaScript:
{Link}
Sowmya ,
use trim function...
smthing like
strObj.trim(":")[1]
Have a look at this article for more ways of implementing javascript trim: {Link}
I looked through these functions trying a few of the examples finding them to behave differently then what I was looking for as a quick fix. When I think of a trim function I am thinking the results return a string minus the leading and trailing spaces.
For you who wanted to remove all spaces, there is no reason to loop through a string to remove them.. just use str.replace(' ',''); end of story.
I ended up writing this little script prototyping String as well, this will remove all leading and trailing spaces leaving the inner string untouched. Hope it helps..
String.prototype.trim = function() {
var str = this;
var firstChar = str.substring(0,1);
while(firstChar == ' '){
str = str.substring(1,(str.length))
firstChar = str.substring(0,1);
}
var lastChar = str.substring(str.length - 1, str.length);
while(lastChar == ' '){
str = str.substring(0,str.length - 1);
lastChar = str.substring(str.length - 1, str.length);
}
return str;
}
I don't like using regexp, but sometimes you need to remove the tabs too, not only the spaces.
The above example is good, but it is very slow!
Using str = str.substr(0, str.length-1) in a loop is not a good practice, just because it copies the entire string a lot of times.
I prefer checking where is the begining and the end of my trimed string, then to cut it at once:
String.prototype.trim = function()
{
var b = 0 ;
var e = this.length - 1 ;
while( this.substr(b, 1).match(/\s/) ) b++ ;
while( this.substr(e, 1).match(/\s/) ) e-- ;
return this.substr(b, e-b+1);
}
Hope this will help somebody!
Previously we are writing to trim a string object ,with your script it's very easy to trim any thing we want very smoothly.
Thnks
I prefer the original author's version, however it can be written as one line rather than 2:
String.prototype.trim = function() {
return this.replace(/^\s+ | \s+$/g,'')
}
I got my jQuery get responce matched exactly with this function.. Preddy helpful function..
Keep up the good work...
P