Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a colon using string replace using Javascript and jQuery [duplicate]

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?

like image 639
tollmanz Avatar asked Jun 29 '11 17:06

tollmanz


3 Answers

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.

like image 176
Chrisdigital Avatar answered Oct 20 '22 11:10

Chrisdigital


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(":", ".");

like image 24
SLaks Avatar answered Oct 20 '22 10:10

SLaks


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(":", ".");
    }
 );
like image 38
Dunes Avatar answered Oct 20 '22 10:10

Dunes