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>