5

I have a simple string that I'm trying to manipulate:

Your order will be processed soon:

I grab the string using:

var html = jQuery('.checkout td h4').html();

I then try to replace the ':' using:

html.replace(":", ".");

When I print it out to the console, the string is the same as the original string. I've also tried making sure that the html variable is of type "string" by doing the following:

html = html + "";

That doesn't do anything. In searching around, it seems that the replace function does a RegEx search and that the ":" character might have a special meaning. I do not know how to fix this. Can someone help me get rid of this stinkin' colon?

tollmanz
  • 3,113
  • 4
  • 29
  • 34

3 Answers3

10

Slightly related...

I couldn't get these answers to work to replace all ":" in a string for the url encoded character %3a and modified this answer by'xdazz' to work: Javascript: Replace colon and comma characters to get...

str = str.replace(/:\s*/g, "%3a");

In your case it would be

str = str.replace(/:\s*/g, ".");

If you wanted to replace all colons with periods on a longer string.

Hope this helps somebody else.

Community
  • 1
  • 1
Chrisdigital
  • 384
  • 3
  • 8
8

The replace function returns a new string with the replacements made.
Javascript strings are immutable—it cannot modify the original string.

You need to write html = html.replace(":", ".");

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Could of sworn I tried that and it didn't work...oh well...it is certainly working now. Thanks! I'll give you the check when it lets me in 9 minutes. – tollmanz Jun 29 '11 at 17:52
1

I think c++ is the only high level language where strings are mutable. This means that replace cannot modify the string it operates on and so must return a new string instead.

Try the following instead

var element = jQuery('.checkout td h4');

element.html(element.html().replace(":", "."));

Or, perhaps more correctly (since you may have multiple elements).

jQuery('.checkout td h4').html(
    function (index, oldHtml) {
        return oldHtml.replace(":", ".");
    }
 );
Dunes
  • 37,291
  • 7
  • 81
  • 97