Replace '-' with '-' in the JavaScript string

I am trying to replace a single โ€œ-โ€ character in a line with double dashes.

2015โ€“09โ€“01T16:00:00.000Z to be 2015-โ€“09-โ€“01T16:00:00.000Z 

This is the code I use, but it does not work:

 var temp = '2015โ€“09โ€“01T16:00:00.000Z' temp.replace(/-/g,'--') 
+5
source share
3 answers

In JavaScript, Strings are immutable. Thus, when changing a string, a new string object will be created with the modification.

In your case, replace replaced the characters, but returns a new line. You need to store this in a variable in order to use it.

For instance,

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

Note The line that you indicated in the question when copying, I realized that this is a different character , but similar to โ€“ and this is not the same as a hyphen ( - ). The character codes for these characters are as follows

 console.log('โ€“'.charCodeAt(0)); // 8211: en dash console.log('-'.charCodeAt(0)); // 45: hyphen 
+16
source

The hyphen character โ€“ which you have in the string is different from the character you have in RegExp - . Although they are alike, they are different characters.

In this case, the correct RegExp is temp.replace(/โ€“/g,'--')

+7
source

Probably the easiest would be to simply use split and join.

 var temp = '2015โ€“09โ€“01T16:00:00.000Z'.split("-").join("--"); 
+4
source

Source: https://habr.com/ru/post/1240790/


All Articles