1

I have a function that override primary types in CoffeeScript, but this function returnin value and I want to change itself.

String::replaceAll = (what, to) ->
    regexPattern = new RegExp(what, "g")
    this.replace regexPattern, to

Now I have to use this in this way:

test = test.replaceAll "sth", "sth2"

I want to use this in this way:

test.replaceAll "sth", "sth2" # only, without assigning

(this = this.replace regexPattern, to # doesn't work)

mitch
  • 2,235
  • 3
  • 27
  • 46

1 Answers1

2

Strings in javascript/coffeescript are immutable and can't be changed once created. So its not possible to have it modify itself, only to return a new value. However you can chain your function as it is currently set up if you like, since it does return a value.

so

test = test.replaceAll(x,y).replaceAll(a,b)

should work fine

References

MDN:

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.

SO:

Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?

Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71