JavaScript Replace()特殊字符并填充在表单中

时间:2017-11-13 18:19:15

标签: javascript html replace

Form1将添加文本,Form2应填充与Form1相同的文本,但使用replace方法进行转换。我在填写Form2中的文本时遇到问题。

<form id="form1">
<input type="text" name="input" value="">
<button type="submit" name="submit" value="submit">Submit</button>
</header>
<div>
    <label>Plain Text:</label>
    <form id="form2">
    <input type="text" name="input" value="" onchange="convertMarkdown()">
</div>
</div>
<script>
    function convertMarkdown() {

        const form = document.getElementById("form1");
        const input = form.querySelector("input");
        const form2 = document.getElementById("form2");
        const convertedMarkdown = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");

        form.addEventListener('submit', (e) => {
            // prevent browser default
            e.preventDefault();

            // contain text content
            const text = input.value;

            // print text content in form1
            form1.textContent = text.text
        });

        form2.addEventListener('onchange', (e) => {
        // prevent browser default
        e.preventDefault();

        // contain text content
        const text = input.value;

        // print converted text in form2
        form2.textContent = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
    };
</script>

1 个答案:

答案 0 :(得分:2)

以下js代码将提供您的预期输出。

&#13;
&#13;
const submit = document.getElementById("submit");
const input = document.getElementById("ip1");

submit.addEventListener('click', (e) => {
  // prevent browser default
  e.preventDefault();
  const convertedMarkdown = input.value.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
  // contain text content
  const text = input.value;

  // print text content in form1
  document.forms["form2"]["input2"].value = convertedMarkdown;
});
&#13;
<form name="form1">
  <input id="ip1" type="text" name="input" value="">
  <button id="submit" type="submit" name="submit" value="submit">Submit</button>
</form>
<div>
  <label>Plain Text:</label>
  <form name="form2">
    <input type="text" name="input2" value="">
  </form>
</div>
&#13;
&#13;
&#13;