【发布时间】:2018-07-07 23:35:08
【问题描述】:
我遇到了一段代码问题,该代码段应该使用正则表达式从元素中删除所有空格,然后更改文档元素的内容。
所以问题是文本必须位于源代码中的 textarea 标记之间,以便它适用于 Firefox 和 chrome。
函数执行后,我尝试为 Firefox 和 chrome 输入测试语句,但它不再起作用。
所以总结一下..它可以在 Firefox 和 chrome 中工作一次,但前提是文本已经在源代码中。我已经看到它在 Internet Explorer 和 Microsoft Edge 中完美运行。不过我更喜欢 Firefox,所以我非常感谢有人指出问题所在。
这是代码:
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>
【问题讨论】:
标签: javascript html css regex function