regular expression

G

gaurav v bagga

hi all,

i am finding it difficult to find a regular expression for following
situation(replace)

a b c d => a,b,c d
a b c => a,b c

i'll apreciate if anyone helps me with this...

regards
gaurav
 
J

Janwillem Borleffs

gaurav said:
i am finding it difficult to find a regular expression for following
situation(replace)

a b c d => a,b,c d
a b c => a,b c

i'll apreciate if anyone helps me with this...

alert("a b c".split(' ').join(',').replace(/(,)([^,]+)$/, ' $2'));


JW
 
E

Evertjan.

gaurav v bagga wrote on 20 jan 2007 in comp.lang.javascript:
i am finding it difficult to find a regular expression for following
situation(replace)

a b c d => a,b,c d
a b c => a,b c

i'll apreciate if anyone helps me with this...

You will have to explain better.

Are a b c and d words, single letters, numbers?
Do you mean any whitespave with your space,
and replace all with a , but the last one??

Try:

t = t.replace(/\s+/g,',').replace(/,([^,]+)$/,' $1')
 
J

Janwillem Borleffs

Janwillem said:
alert("a b c".split(' ').join(',').replace(/(,)([^,]+)$/, ' $2'));

Alternative, using look ahead assertion:

alert("a b c".split(/\s(?![^\s]+$)/).join(', '));


JW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top