简体   繁体   中英

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?

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>

\ 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, "\\:");

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM