javascript - 移动字符串的各个部分

标签 javascript string match

假设我有一个字符串:

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 / 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>');

关于javascript - 移动字符串的各个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35941739/

相关文章:

javascript - CSS 模块在 Codesandbox 中不起作用 - 即使文件存在也无法找到

javascript - 了解箭头函数参数

javascript - 仅当字符串后面没有左方括号时才替换字符串,即 [

java - java中如何查找一个字符串对象重复了多少次?

MySQL 匹配 2 个字段

javascript - 浏览器检测所需的实际图像大小

php - 字符串函数在 PHP 中是 ASCII 安全的吗?

Java字符串计算器,第一个数字为负数

如果不匹配,grep 返回 0

javascript - 从用户输入中查找 csv 文件内容的精确值