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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular expression 1

Status
Not open for further replies.

craigward

Programmer
Nov 13, 2007
230
0
0
GB
Hi All,
I have just spent a while searching how to use regular expression to strip out spaces in a string and replace them with ‘,’ I don’t seem to be getting anywhere and was hoping someone could explain how to do it.

So for example:

Mystring = “a b c d”

My string would end up looking like the following

Mystring = “A’,’b’,’c’,’d”

Thanks for any help.
 
--
s.replace(/\s/g,",");
"a,b,c,d"

_________________
Bob Rashkin
 
or if you really want the quotes around your commas:
--
s.replace(/\s/g,"\',\'")

_________________
Bob Rashkin
 
Thanks for that it did the trick. Sorry to be a pain but can you explain in simple terms the meaning of the various characters here? just so i know for next time (/\s/g,"\',\'")
 
In Javascript syntax, a regular expression pattern is bounded by "/". "\s" is defined: "matches a single white space character". After the ending "/" come flags, in this case the "global" flag meaning "all". The other flag, "i", means "ignore case". So that's the patter: "/\s/g" == "match all occurrences of a single white space character".

The "<string>.replace()" syntax is "(pattern, replacement)". The "replacement" in this case is "\',\'". For your own reasons you wanted the spaces replaced with "','" including the single-quotes. That turns out to be a little awkward since the quotes have pattern-matching meaning. To get around that, all regular expression handlers that I know of, including Javascipt, use "escape sequences" which just means that if a character is preceded by "\" use the literal character rather than what it might mean in a pattern. So "\'" means "'".

_________________
Bob Rashkin
 
Many thanks for the explanation it is very helpful.
 
Hi

Sorry, but there is no need to escape the single quotes ( ' ) there. [tt]replace()[/tt]'s second parameter is a string [sup](*)[/sup], so it has no special escaping requirements. You would need to escape them only if the string literal itself would be delimited with single quotes :
Code:
[blue]>>> "a b c d".replace(/\s/g,"\',\'")[/blue]
[red]"a','b','c','d"[/red]
[blue]>>> "a b c d".replace(/\s/g,"','")[/blue]
[red]"a','b','c','d"[/red]
[blue]>>> "a b c d".replace(/\s/g,'\',\'')[/blue]
[red]"a','b','c','d"[/red]
[small](*) - In this case. Could be a function too. But not a regular expression.[/small]

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top