5

I am trying to replace a single dash '-' character in a string with double dashes.

2015–09–01T16:00:00.000Z

to be

2015-–09-–01T16:00:00.000Z

This is the code I am using but it doesn't seem to be working:

var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
Tushar
  • 85,780
  • 21
  • 159
  • 179
runtimeZero
  • 26,466
  • 27
  • 73
  • 126

3 Answers3

16

In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.

In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.

For example,

var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');

Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to and it is not the same as hyphen (-). The character codes for those characters are as follows

console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
Tushar
  • 85,780
  • 21
  • 159
  • 179
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
7

The hyphen character you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.

The correct RegExp in this case is temp.replace(/–/g,'--')

techfoobar
  • 65,616
  • 14
  • 114
  • 135
4

Probably the easiest thing would be to just use split and join.

var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");
whatoncewaslost
  • 2,216
  • 2
  • 17
  • 25
  • As explained in other answers, this should work only when the character you're splitting by is same as used in the string. – Tushar Jan 17 '16 at 07:16