javascript 如何为句子中的每个空 space 重复执行替换函数
javascript how to repeat the replace function to execute for every empty space in a sentence
我正在编写一个程序,需要解析用户在文本字段中输入的句子中的每个单词,并执行将句子中的每个单词输出到单独行的工作。我非常接近,我能够通过每个 space 上的替换函数来替换为
,但它只对第一个 space 执行此操作。我怎么能让它在每个 space 时重复它,不知道用户将在他的句子中输入多少个单词?到目前为止,这就是我所拥有的。
<header>
<h1>Parse Test</h1>
</header>
<br>
<p>Please enter facts:</p>
<input id="inp" type="text">
<br>
<br>
<button type="button" onclick="pass()">Process</button>
<br>
<p id="iop"></p>
<br>
<script>
function pass() {
var lx = document.getElementById("inp").value;
var tx = lx.replace(" ","<br>");
document.getElementById("iop").innerHTML = tx;
}
</script>
您可以传递一个正则表达式,并告诉它使用 g
标志全局应用:
var tx = lx.replace(/ /g, '<br>');
简化的工作示例:
console.log('A few different words'.replace(/ /g, '<br>'));
我正在编写一个程序,需要解析用户在文本字段中输入的句子中的每个单词,并执行将句子中的每个单词输出到单独行的工作。我非常接近,我能够通过每个 space 上的替换函数来替换为
,但它只对第一个 space 执行此操作。我怎么能让它在每个 space 时重复它,不知道用户将在他的句子中输入多少个单词?到目前为止,这就是我所拥有的。
<header>
<h1>Parse Test</h1>
</header>
<br>
<p>Please enter facts:</p>
<input id="inp" type="text">
<br>
<br>
<button type="button" onclick="pass()">Process</button>
<br>
<p id="iop"></p>
<br>
<script>
function pass() {
var lx = document.getElementById("inp").value;
var tx = lx.replace(" ","<br>");
document.getElementById("iop").innerHTML = tx;
}
</script>
您可以传递一个正则表达式,并告诉它使用 g
标志全局应用:
var tx = lx.replace(/ /g, '<br>');
简化的工作示例:
console.log('A few different words'.replace(/ /g, '<br>'));