-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?

Axifive
  • 1,159
  • 2
  • 19
  • 31

5 Answers5

9

var str = "19-12-2018";
var newstr = str.split('-').reverse().join('-');
console.log(newstr);
JO3-W3B-D3V
  • 2,124
  • 11
  • 30
2

Do split('-') first:

var str = "19-12-2018";
str = str.split('-').reverse().join('-');
console.log(str);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
2

You need this:

str.split('-').reverse().join('-')
Nick
  • 3,454
  • 6
  • 33
  • 56
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"
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
-1

Try this one

var str = "19-12-2018".split('-');
var newstr=str[2]+"-"+str[1]+"-"+str[0];
Zain Farooq
  • 2,956
  • 3
  • 20
  • 42
Mahesh Odedra
  • 59
  • 1
  • 7