Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string question

Status
Not open for further replies.

Suppy

Technical User
Jul 22, 2002
12
RO
How can i create a string function that will give me the string but with out the spaces from the front or the back of the string
 
It sounds like you want a string trimming function. This is the kind of thing I use:

function trim(onestring)
{
var whitespace='\t\n\r ';
var newstring=onestring, oi=0;

var onechar=newstring.charAt(oi);
while (whitespace.indexOf(onechar) > -1)
{
oi++;
if (oi==newstring.length) return '';
onechar=onestring.char(oi);
}

newstring = newstring.substr(oi);

oi=newstring.length-1;
onechar=newstring.charAt(oi);
while (whitespace.indexOf(onechar) > -1)
{
oi--;
if (oi<0) return '';
onechar=newstring.charAt(oi);
}

newstring=newstring.substr(0, oi + 1);
return newstring;
}
 
Thank you for sending me the script.I am a rookie in Javascript but i want to learn.
But a friend of mine told me somthing about regular expessions. Is it possible to write all the code that you gave me in one line with regular expressions?
Thanks
Suppy
 
I'm not adept at regular expressions myself, but some of the techies here speak regular expressions like their mother tongue. :)#
 
ok thanks anyway.
but i have one more question.
how do i use your function?
is it correct this way
var x=trim(&quot;some thing&quot;)
response.write(x)
on my screen will apear &quot;something&quot; in one word not in two
 
The function I wrote will trim all leading and trailing white space from a string, but leave anything inside alone. Did you want ALL white space removed, sothewholestringisonebigword?

What I wrote will give you:

var oldstring=' some thing ';
var newstring=trim(oldstring);

which will result in 'some thing'

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top