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(' ', '-')
?
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(' ', '-')
?
3 Answers
Reset to default 8It's better to use:
var string = "find this and find that".replace(/find/g, "found");
to replace all occurrences.
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 + '" bees "' + 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.
For the most regular expressions, you can do it by testing with the regular expression tester.