Anoniem Anoniem
Anoniem Anoniem

Reputation: 2005

Cut and replace in javascript string

I got the following string:

"14-10-2013 03:04"

And I would like a function which replaces the part where the '10' is now, with the part where the '14' is now. How can I do so? I know there is something like split but I'm not too experienced with it.

So far:

var string = '14-10-2013 03:04';
var firstPart = string.split("-", 1);
alert(firstPart);

But I don't know how to get the second part (the '10') in a variable.

Upvotes: 0

Views: 211

Answers (1)

SheetJS
SheetJS

Reputation: 22905

For the particular string format (converting "xx-yy-..." to "yy-xx-..."), a simple replace will do:

"14-10-2013 03:04".replace(/(\d\d)-(\d\d)/,"$2-$1")

Explanation:

The regular expression /(\d\d)-(\d\d)/ matches two digits, followed by a dash, followed by two more digits. The parentheses denote capture groups which can be referenced in the second argument. In this case, for the string "14-10-2013 03:04", the substring "14-10" matches the regular expression and the two captured texts are "14" and "10".

In the second argument, use $1, $2, ... to specify where the captured text should be inserted. In this case, "$2-$1" will write the second captured text (14), followed by a dash, followed by the first captured text (10).

For more information, see the MDN Documentation on String.prototype.replace.

Upvotes: 2

Related Questions