0

I'm curious about the following code and why it is that replace is not replacing the second underscore in string2. It was my assumption that replace is going character by character through the string looking to replace the given value with the new value, but that apparently is not exactly the case.

const string1 = "hello_world"
const string2 = "hello__world"

string1.replace('_', '-') // 'hello-world'
string2.replace('_', '-') // 'hello-_world'
rockchalkwushock
  • 1,143
  • 2
  • 9
  • 19
  • 1
    `.replace` only replaces the first match when matching against a string. – Nicholas Tower Sep 26 '18 at 17:05
  • 1
    see the second paragraph here:: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Parameters – Mark Sep 26 '18 at 17:05
  • 1
    First paragraph: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – PM 77-1 Sep 26 '18 at 17:06
  • 1
    https://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string – epascarello Sep 26 '18 at 17:07

3 Answers3

0

You will need to use a regex modifier, in this case g. This replaces all instances of the pattern.

const string1 = "hello_world"
const string2 = "hello__world"

console.log(string1.replace(/_/g, '-'))
console.log(string2.replace(/_/g, '-'))
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
0

In order for it to work as intended you have to use a regex to match all the underscores in your string like so

const string1 = "hello_world"
const string2 = "hello__world"

string2.replace('_', '-') // 'hello-_world'
string2.replace(/_+/g, '-') // 'hello-world'
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
Joe25
  • 136
  • 7
0

Here's an answer for your question. .replace() only replace the first character. You can know more about replace() here

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
HHSE123
  • 67
  • 10