假设我有一个字符串:
var mystring = "01/27/2016";
然后我想检查该字符串是否包含 /
:
if(mystring.match("/")){
//Then transform "01/27/2016" to "2016-01-27"
}
我怎样才能实现它? 最好的问候
最佳答案
您可以使用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>');
关于javascript - 移动字符串的各个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35941739/