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
87.4k21 gold badges164 silver badges182 bronze badges
asked Jan 17, 2016 at 6:56
0

3 Answers 3

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
87.4k21 gold badges164 silver badges182 bronze badges
answered Jan 17, 2016 at 6:58
Sign up to request clarification or add additional context in comments.

1 Comment

Not only in JavaScript but nearly in all major languages string variables are immutable.
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,'--')

answered Jan 17, 2016 at 6:59

Comments

4

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

var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");
answered Jan 17, 2016 at 6:58

1 Comment

As explained in other answers, this should work only when the character you're splitting by is same as used in the string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.