Javascript Replace Hypens With Space
Solution 1:
Just for reference:
var datepickr = 'Jun-29-2011';
datepickr.replace("-", " "); // returns "Jun 29-2011"
datepickr.replace(/-/, " "); // returns "Jun 29-2011"
datepickr.replace(/-/g, " "); // returns "Jun 29 2011" (yay!)
The difference is the global modifier /g
, which causes replace to search for all instances. Note also that -
must be escaped as \-
when it could also be used to denote a range. For example, /[a-z]/g
would match all lower-case letters, whereas /[a\-z]/g
would match all a's, z's and dashes. In this case it's unambiguous, but it's worth noting.
EDIT
Just so you know, you can do it in one line without regex, it's just impressively unreadable:
while (str !== (str = str.replace("-", " "))) { }
Solution 2:
.replace
is supposed to take a regular expression:
var b = datepickr.replace(/-/g,' ');
I'll leave it as an exercise to the reader to research regular expressions to the full.
(The important bit here, though, is the flag /g
— global search)
Solution 3:
Try this:
var datepickr = 'Jun-29-2011';
var b = datepickr.replace( /-/g, ' ' );
The /g
causes it to replace every -
, not just the first one.
Solution 4:
var b = 'Jun-29-2011'.replace(/-/g, ' ');
Or:
var b = 'Jun-29-2011'.split('-').join(' ');
Solution 5:
replace
works with regular expressions, like so:
> "Hello-World-Hi".replace(/-/g, " ")
Hello World Hi
Post a Comment for "Javascript Replace Hypens With Space"