Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace '-' with '--' in a JavaScript string [duplicate]

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,'--')
like image 676
runtimeZero Avatar asked Jan 17 '16 06:01

runtimeZero


2 Answers

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
like image 57
thefourtheye Avatar answered Oct 04 '22 10:10

thefourtheye


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,'--')

like image 39
techfoobar Avatar answered Oct 04 '22 09:10

techfoobar