Click to See Complete Forum and Search --> : truncate-function?


shumway
03-24-2003, 06:42 AM
What is the truncate-function called in Javascript?

I want a trunc-function to do following:

MyText = " Spaces everywhere ";

MyText = trunc( MyText );

MyText is now: "Spaces everywhere"

Nicodemas
03-24-2003, 06:59 AM
I don't know any Javascript that does this.. however, VBSCript does.

You could possibly do it this way:

<SCRIPT LANGUAGE="VBScript">
myString = " lots of spaces "
myNewstring = Trim("myString")

myNewstring = "lots of spaces"
</SCRIPT>

shumway
03-24-2003, 07:16 AM
Thankyou!

But how do all you javascript-junkies do that then if there isnt such a function? Do you just dont care if the user types spaces first in their forms or do you do it in another way?

requestcode
03-24-2003, 07:39 AM
There is not a Trim function in JavaScript. You can use regular expressions to remove spaces at the end of a string. Here is an example using the replace() method of the string object with a regular expresion.
<script language="javascript">
re=/\s+$/g
var mystringa="Lots of spaces "
var mystringb=mystringa.replace(re,"")
</script>

Here is a link describing regular expressions:
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/regexp.html#1010922

shumway
03-24-2003, 08:03 AM
Thank_you_2!

Will check out that!

Scriptage
03-24-2003, 08:31 AM
just adding to requestcode's code:

function trunc(string){
var myString = string.replace(/\s*/,"");
myString = myString.replace(/\s+$/,"");
return myString;
}
var MyText = " Spaces Everywhere ";
MyText = trunc(MyText);
alert("'"+MyText+"'");

regards
Carl

shumway
04-03-2003, 01:46 AM
Thanks - exactly what I wanted even though I think there should be a built-in function for this :-)