...

View Full Version : splitting by spaces



Garadon
03-20-2004, 11:02 PM
splitting by spaces:

I got the following code:

var test=" v2 v3 v4 v1 ";
test=test.replace(/^\s+|\s+$/g,'');
test=test.replace(/([\s]+\s)/g,' ');
test=test.split(' ');
alert(test)


basicly the 1st replace remove spaces on eeach side of the string
2nd replace takes groups spaces inside the string an replace with 1 space.
the split make an array splitting the string by space.

array(v2,v3,v4,v1)

my question is are there a better regexp that can achieve the same goal on 1 line that I use 3 lines to.

Willy Duitt
03-21-2004, 12:14 AM
I'm still struggling with Regular Expressions myself.
But this should work.

<script type="text/javascript">
var test=" v2 v3 v4 v1 ";
test=test.replace(/^\s+|\s(?=\s)|\s+$/g,'').split(/\s/);
document.write(test)
</script>

.....Willy

Garadon
03-21-2004, 07:00 AM
ty it seem to do :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum