trimming white space in JS easily

I’m still crook, as my Twitter tweets will have let you know, but I thought I’d jump online and do a quick post. I got up this morning feeling worse than ever, but ecided to give lectures a go. Got showered dressed and out the door, before the migraine and sinus went “MEH!!!”; so I got some Night-and-Day and the pharmacy and went home to bed….

Anyways, here’s a quick script to deal with white-space in JavaScript strings, and remove both leading and trailing white-space with one easy function:

<script language="javascript">
function trim(str, chars) {
return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
</script>

Nothing flash or earth-shattering here, just thought it might be useful.

I’ll try to be coherent later, and post some more tuts. I won’t have much to say myself, as talking about sleeping and being in bed is boring for everyone, including the writer (me).

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: