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
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
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/
literally2nd 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/
literally3rd 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>');
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>');
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);
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"
}
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')