Skip to content
Advertisement

Replace colon in javascript before sending the form

I have a text input search field. I’d like to add an escape backslash to any colon entered by the user. This is what I have right now:

<form role="form" action="..." method="get">
  <div>
    <input id="input" type="text" name="q">
    <button id="search_button" type="submit">Go!</button>
    </span>
  </div>
</form>

<script type="text/javascript">
  document.getElementById("search_button").addEventListener('click', function() {
    let text = document.getElementById('input').value;
    let regex = /:/gi;
    let new_text = text.replaceAll(regex, ":");
  });
</script>

It doesn’t seem to work, though: the string sent to the ‘q’ parameter has the colon without the escape character. What am I missing?

Advertisement

Answer

Even when fixing the replacement with the additional backslash, your code still wont work because you also need to change the value of the form field with its new value, as follows “new code”:

<form role = "form" action="..." method="get">
<div>
    <input id="input" type="text" name="q">
        <button id="search_button" type="submit">Go!</button>
    </span>
</div>
</form>

<script type="text/javascript">
document.getElementById("search_button").addEventListener('click', function () {
    let text = document.getElementById('input').value;
    let regex = /:/gi;
    let new_text = text.replaceAll(regex, "\:"); // fix
    document.getElementById('input').value =  new_text; // new code
});
</script>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement