0

Say I have a string:

var mystring = "01/27/2016";

I want then to check if that string contains /:

if(mystring.match("/")){
//Then transform "01/27/2016" to "2016-01-27"
}

How could I achieve it? Best Regards

user1665355
  • 3,324
  • 8
  • 44
  • 84
  • Split the string ([`.split("/")`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split)) and check the length of the array. If there is only one element in the array then there is no `/` in the string. Otherwise you have the individual date parts to create a string in the required format. – Andreas Mar 11 '16 at 13:44
  • Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – Hatchet Mar 11 '16 at 13:44

5 Answers5

2

You may use String#replace:

/(\d+)\/(\d+)\/(\d+)/gi

  • 1st Capturing group (\d+)

    \d+ match a digit [0-9]

    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]

  • \/ matches the character / literally

  • 2nd Capturing group (\d+)

    \d+ match a digit [0-9]

    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]

  • \/ matches the character / literally

  • 3rd Capturing group (\d+)

    \d+ match a digit [0-9]

    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]

// is replacing
document.write('01/27/2016'.replace(/(\d+)\/(\d+)\/(\d+)/gi, '$3-$1-$2') + '<br>');

// is not replacing
document.write('01.27.2016'.replace(/(\d+)\/(\d+)\/(\d+)/gi, '$3-$1-$2') + '<br>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Solution without regex and with split method

var mystring = "01/27/2016";
var t = mystring.split('/')
var res = t[2] + '-' + t[0] + '-' + t[1];
document.write('<pre>' + JSON.stringify(res,0,2) + '</pre>');

Another solution using Array#join function

var mystring = "01/27/2016";
var t = mystring.split('/')
var res = [t[2], t[0], t[1]].join('-');
document.write('<pre>' + JSON.stringify(res,0,2) + '</pre>');
isvforall
  • 8,768
  • 6
  • 35
  • 50
0

You can do this:

var myString = "01/27/2016";

if(myString.match("/")) {
  var array = myString.split("/");
  myString = array[2] + "-" + array[0] + "-" + array[1];
}

document.write(myString);
Pierre C.
  • 1,426
  • 1
  • 11
  • 20
0

In you want to check if your string contains some char or another string use https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

in your example

 if(mystring.indexOf('/') > -1){
   //Then transform "01/27/2016" to "2016-01-27"
   }
dominiczaq
  • 343
  • 2
  • 9
0

I recommend use the library moment.js

If you want change date formats MM/DD/YYYY to YYYY-MM-DD

var mystring = "01/27/2016",
    dateformatted = moment(mystring,'MM/DD/YYYY').format('YYYY-MM-DD')
Joaquinglezsantos
  • 1,510
  • 16
  • 26