Replacing a colon using replace string using Javascript and jQuery

I have a simple line that I am trying to manipulate:

Your order will be processed shortly:

I take a string using:

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

Then I try to replace ':' using:

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

When I print it to the console, the line is the same as the original line. I also tried to make sure that the html variable is of type β€œstring” by doing the following:

 html = html + ""; 

It does nothing. When searching around, it seems like the replace function is doing a search in RegEx and that the β€œ:” character may have special meaning. I do not know how to fix this. Can someone help me get rid of this colon?

+4
source share
4 answers

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

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

+6
source

A little bit connected ...

I could not get these answers to work, to replace all the ":" in the string for the encoded URL of character% 3a and change this by'xdazz answer to work: Javascript: Replace the colon and comma to get ...

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

In your case it will be

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

If you want to replace the entire colon with longer lines.

Hope this helps someone else.

+5
source

I think C ++ is the only high-level language where strings are mutable. This means that replace cannot change the line on which it works, and therefore must return a new line.

Try instead

 var element = jQuery('.checkout td h4'); element.html(element.html().replace(":", ".")); 

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

 jQuery('.checkout td h4').html( function (index, oldHtml) { return oldHtml.replace(":", "."); } ); 
+1
source

This can also be done using substring() :

 var str = "Your order will be processed soon:"; var str = str.substring(0,(str.length - 1)) + '.'; alert(str); 

JS Fiddle demo .

Although this is for additional information (hence CW), and not for the serious assumption that you should do it this way, since the colon ( : should always be the last character, and if it were not, then other words will be abbreviated.

Link:

0
source

All Articles