-5

I want to convert the string "19-12-2018" to "2018-12-19" How can I do it?

var str = "19-12-2018";
    str.split('').reverse().join('')  //returns 8102-21-91"

how to do this?

3

5 Answers 5

9

var str = "19-12-2018";
var newstr = str.split('-').reverse().join('-');
console.log(newstr);

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

Comments

2

I call the split function passing dash which separate each part of the string

str.split("-").reverse().join("-");

Description of functions used

  1. String.prototype.split(): The split() method turns a String into an array of strings, by separating the string at each instance of a specified separator string.
const chaine = "Text";
console.log(chaine.split('')); // output ["T", "e", "x", "t"]
  1. Array.prototype.reverse(): The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
const characters = ["T", "e", "x", "t"];
console.log(characters.reverse()); // output ["t", "x", "e", "T"]
  1. Array.prototype.join(): The join() method creates and returns a new string by concatenating all of the elements in an array
const reverseCharacters = ["t", "x", "e", "T"];
console.log(reverseCharacters.join('')); // output "txeT"

Comments

2

Do split('-') first:

var str = "19-12-2018";
str = str.split('-').reverse().join('-');
console.log(str);

Comments

2

You need this:

str.split('-').reverse().join('-')

Comments

-1

Try this one

var str = "19-12-2018".split('-');
var newstr=str[2]+"-"+str[1]+"-"+str[0];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.