user4571629
user4571629

Reputation: 450

jQuery replace character with another

Let's say I have:

<h1>Win $50<h1>

I need to change the $ sign to € with jQuery
So I can do it like that:

$('h1').text( $('h1').text().replace('$', '€') );

But what if I have something like that:

<h1>Win $50 and Get $100</h1>

It only change the first one, How can I change it all?

Upvotes: 4

Views: 24924

Answers (3)

Jeremy Thille
Jeremy Thille

Reputation: 26370

With a regex.

txt = $('h1').text().replace(/\$/g, '€')
$('h1').text(txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Win $50 and get $100</h1>

g stands for "global" (all instances)

As RafH said, $ is a special character in regex, so it needs to be escaped with \.

Upvotes: 5

Howard Renollet
Howard Renollet

Reputation: 4739

Here's a helper function that's a part of my utility library that I add into every piece of code that I write. Feel free to use it any way you like.

String.prototype.replaceAll = function (stringFind, stringReplace) {
    var ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g");
    return this.replace(ex, stringReplace);
};

It adds a replaceAll function to all strings so you don't have to constantly use RegEx throughout your code.

You can use it like this

str.replaceAll("$", "€");

Here's an example:

String.prototype.replaceAll = function (stringFind, stringReplace) {
  var ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g");
  return this.replace(ex, stringReplace);
};

var str = "Win $50 and Get $100";

document.body.innerHTML = str.replaceAll("$", "€");


EDIT Test cases per comment below:

String.prototype.replaceAll = function (stringFind, stringReplace) {
  var ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g");
  return this.replace(ex, stringReplace);
};

var str = "test test abc test abc $%& test $%& $%&. test. abc $%& . .";
document.body.innerHTML = str  + "<br />";
document.body.innerHTML += str.replaceAll(".", "") + "<br />";
document.body.innerHTML += str.replaceAll("%&", "") + "<br />";
document.body.innerHTML += str.replaceAll("test", "") + "<br />";
document.body.innerHTML += str.replaceAll("a-z", "") + "<br />";


Update

Per the comments from Danilo below (Thank you!), the original function would not allow for certain special characters, and would misbehave if a text range was entered into the replaceAll() function. In my own code, I had not come across these cases as of yet.

Per this answer, I have updated my function so that it now escapes the RegEx to be more efficient in the provided test case scenarios.

Upvotes: 2

RafH
RafH

Reputation: 4544

Use regexp with g flag

$('h1').text( $('h1').text().replace(/\$/g, '€') );

Upvotes: 9

Related Questions