2

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?

Aalexander
  • 4,987
  • 3
  • 11
  • 34
HBMCS
  • 686
  • 5
  • 25
  • Does this answer your question? [How to escape ":"?](https://stackoverflow.com/questions/4791817/how-to-escape) – pilchard Jan 02 '21 at 14:11

3 Answers3

2

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>
GetSet
  • 1,511
  • 2
  • 10
  • 13
1

\ is a special character in string used in escape sequences. If you want to literally add a \ to a string you have to escape it as well.

let new_text = text.replaceAll(regex, "\\:");
derpirscher
  • 14,418
  • 3
  • 18
  • 35
1

Because the backslash have a special meaning you have to escape this character.

You can easily do it by \\:

<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, "\\:");
    document.getElementById('input').value =  new_text; // new code

  });
</script>
Aalexander
  • 4,987
  • 3
  • 11
  • 34