-1

I'm having trouble with a segment of code that is supposed to remove all the spaces from an element using a regular expression and then change the contents of the documents element.

So the problem is that the text has to be in between the textarea tags in the source code in order for it to work for Firefox and chrome.

After the function has executed and I try and type in a test sentence for Firefox and chrome it doesn't work again.


So to sum it up..it's possible to work once in Firefox and chrome but only if the text is already in the source code. I've seen it work perfectly in Internet Explorer and Microsoft edge. I prefer Firefox though so I'd really appreciate someone pointing out what is wrong.

Here's the code:

function removeSpaces() {
  var str = document.getElementById("contents").innerHTML;
  while (str.search(/\s/img) > -1) {
    var txt = str.replace(/\s/img, "");
    document.getElementById("contents").innerHTML = txt;
    str = document.getElementById("contents").innerHTML;
  }
}
<html>

<body>
  <textarea id="contents" rows="5" cols="20">
    This is a sentence.
    This is another sentence.
    Hello everyone.
    </textarea>

  <p>Click button to remove spaces.</p>

  <button type="button" onclick="removeSpaces()">Try it</button>

  <script>
    /* js function */
  </script>
</body>

</html>


Here is the Tryit Editor for W3Schools

Niveditha Karmegam
  • 742
  • 11
  • 28
pditf4me
  • 25
  • 6

1 Answers1

0

Your problem is likely to have less to do with the browser and more to do with user modifications to the field.

The innerHTML of a textarea is its default value. Use value to get and modify its current value.

You should almost never touch the innerHTML of a textarea. Use the value property instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335