J. Scott Elblein
J. Scott Elblein

Reputation: 4283

Small issue with String.Replace()

Not being too versed with JS yet, I've run into a weird issue where it seems like .replace() should be working but isn't.

I'm just trying to take a string (from an element ID) that has text + digits, replace the digits with a RegEx pattern, then replace the original text in that ID with the original text + new digits.

My HTML sample:

<html>
  <body>

    <p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>

    <p id="demo">Movies: 1234!</p>

    <button onclick="myFunction()">Try it</button>

  </body>
</html>

My JS:

function myFunction() {

  // Get all the text in #id=demo
  var str = document.getElementById("demo"); 

  // RegEx pattern to find ": <some digits>"
  var pat = /\:\s?\d*/;

  // Replace the digits
  var res = str.replace(pat, ': 54321');

  // Doesn't work (as a test) ...
  //res = " hi"

  // Replace the text in id=demo with original text + new digits.
  str.innerHTML = res;

  // Doesn't work (as a test) ...
  //document.getElementById("demo").innerHTML = res;
}

At the moment, after clicking the button in the page, nothing happens.

This might help out a bit too: https://codepen.io/stardogg/pen/aboREmL

Upvotes: 1

Views: 64

Answers (3)

Djaouad
Djaouad

Reputation: 22776

In the same way you're setting the innerHTML in the last line of your function, innerHTML is also what you should be applying the replace on:

function myFunction() {
  var str = document.getElementById("demo");

  var pat = /\:\s?\d*/;

  var res = str.innerHTML.replace(pat, ': 54321');

  str.innerHTML = res;
}
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>

<p id="demo">Movies: 1234!</p>

<button onclick="myFunction()">Try it</button>

Upvotes: 1

Abito Prakash
Abito Prakash

Reputation: 4770

You need to extract text from the element before replacing.

//Replace the digits
var res = str.innerHTML.replace(pat, ': 54321');

Upvotes: 0

Aaron Osborn
Aaron Osborn

Reputation: 59

Your str variable is not equal to the text node within the element, but rather the element itself. To make str equal to the text within the element, try the following.

var str = document.getElementById("demo").innerText;

Upvotes: 0

Related Questions