macmonkey
macmonkey

Reputation: 25

Find and replace in Javascript, unless already inplace

I want to premise this with the fact that I am super new to JS.

I'm looking to do a find and replace with JS. The twist is that I want the find and replace do not change anything if the result is already in place (if that makes any sense?)

My example is that I want run the JS to add a "®" a word, but not to add it if the symbol is already present.

Thanks a lot for your help, Harry

$("body").children().each(function () {
    $(this).html( $(this).html().replace(/Hello/g,"Hello®") );
});

Upvotes: 1

Views: 118

Answers (3)

cnocon
cnocon

Reputation: 43

I would recommend working with Regular Expressions until you've uncovered a pattern that eliminates "matches" where the symbol already exists. Also, don't forget to check for the various entities, such as ®, that are used for this symbol.

There are some great regular expression testers out there. I recommend Debuggex

Upvotes: 0

tuhin47
tuhin47

Reputation: 6058

Here is the solution using regex /(^|\s)Hello(\s|$)/g

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <p>Hello</p>
  <p>Hello®</p>
</body>
<script>
  $("body").children().each(function() {
    $(this).html($(this).html().replace(/(^|\s)Hello(\s|$)/g, "Hello®"));
  });
</script>

</html>

Upvotes: 0

Vivek Jain
Vivek Jain

Reputation: 2864

First check if "®" already available or not using $(this).html().indexOf("®") === -1 and if this condition return true then replace.

$("body").children().each(function () {
    if($(this).html().indexOf("®") === -1) {
      $(this).html( $(this).html().replace(/Hello/g,"Hello®") );
    }
});

Upvotes: 1

Related Questions