views:

94

answers:

4

Hi,

I'm trying to work out what regular expression I would need to take a value and replace spaces with a dash (in Javascript)?

So say if I had North America, it would return me North-America ?

Can I do something like var foo = bar.replace(' ', '-') ?

Thanks

+5  A: 

Yes, you can. Why didn't you try this before asking?

tangens
Be aware! Like @alexander-shvetsov explains in his answer, `bar.replace(' ', '-')` only replaces the first occurence of " ".
tangens
+3  A: 

It's better to use:

var string = "find this and find that".replace(/find/g, "found");

to replace all occurrences.

Alexander Shvetsov
Sorry for being dumb but how would I do that in my case?
Rich
var foo = bar.replace(/\ /g, '-');this means, find all regexp matches - regexps in js are surrounded by '/', with option - find all 'g', spaces ('\ ' - escaped) and replace by '-'.
Alexander Shvetsov
Why do you think it's better to use this than `bar.replace(' ', '-')`?
tangens
Thanks a lot, much appreciated!!
Rich
Also worth noting that bar.replace(' ', '-') doesn't replace all occurrences. So the regex version is definitely the best way to go.
Jamie
tangens, string.replace() in js replaces only first occurrence.
Alexander Shvetsov
@alexander-shvetsov: Thanks, I didn't knew this difference between java and javascript.
tangens
The OP actually asked for "spaces" (plural) to be replaced by "a dash" (singular). If `North___America` (3 underscores there, representing 3 spaces) should be changed to `North-America` (one dash, as requested), then you'd need a different regular expression.
Peter Hansen
+2  A: 

The best source of information for regular expressions in various languages that I've found is Regular-Expressions.info (and I linked directly to the Javascript section there).

As for your particular question, yes, you can do something like that. Did you try it?

var before = 'North America';
var after = before.replace(/ +/g, '-')
alert('"' + before + '" becomes "' + after + '"');

Use the site I showed you to analyze the regex above. Note how it replaces one or more spaces with a single hyphen, as you requested.

Peter Hansen
+1  A: 

For the most regular expressions, you can do it by testing with the regular expression tester.

unigg
Nice little tool.
Chuck Conway