字符串替换javascript

时间:2012-07-25 00:13:02

标签: javascript regex

  

可能重复:
  Fastest method to replace all instances of a character in a string = Javascript
  How to replace all points in a string in JavaScript

我有一个字符串2012/04/13。我需要将/替换为-。我怎么能这样做?

var dateV = '2012/04/13';
dateV= dateV.replace('/','-');

它只替换字符串(/)中的第一个/而不是全部2012-04/13。我该怎么做才能纠正这个问题?

2 个答案:

答案 0 :(得分:3)

您需要使用全局正则表达式选项进行全局正则表达式替换。这应该适合你:

var dateV = '2012/04/13';
var regex = new RegExp("/", "g"); // "g" - global option
dateV = dateV.replace(regex, "-");
console.log(dateV);

答案 1 :(得分:0)

使用

dateV= dateV.replace(/\//g,'-');
相关问题