0

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.

2
  • 3
    show us your attempt. And what's your expected output? Commented Oct 14, 2013 at 7:24
  • Updated the main post. Commented Oct 14, 2013 at 7:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Nirk can you edit your answer and give little explanation on the regular expressions you used. That can be helpful for others who are beginners (like me :)) and if they are referring to this question in future for similar kind of problem
@UDB I edited my answer. Let me know if something is unclear
@Nirk thanks for edit and explanation, the solution is more clear now to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.