0

When I run this script with "\d+" as pattern value, the regex doesn't work as I expected. When I escape the backslash it works. Is the backslash the only character that I have to escape?

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Enter a number:</p>
<form id="form">
    <script type="text/javascript">
        var form = document.getElementById( 'form' );
        var input = document.createElement( 'input' );
        input.name = 'amount';
        input.type = 'number';
        input.pattern = "\\d+";
        form.appendChild( input );
    </script>
    <br /><br />
    <input type="submit" value="OK"/>
</form>
</body>
</html>

2 Answers 2

2

You have to escape the backslash character in a string used as a RegEx expression just as you would in any JavaScript string.

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

var home = "c:\\temp";

https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Escaping_Characters

Sign up to request clarification or add additional context in comments.

6 Comments

I don't think he wants to add a backslash but a number. the backlash should be escaped because it's in the string
Isn't that what I put? I don't really see the difference between my answer and your answer.
BTW - Let me know which bit of my answer you think is unclear and I'll happily change it.
your block quotes requires code format. the line with the file path.
OK, fixed. I've left the code in the quote blocks to make it clear that all that content is from MDN.
|
2

the back slash must be escaped as part of the strings syntax.

2 Comments

JavaScript recognises escape sequences in single quote delimited strings. Using single quotes won't help here.
seems like it, I've confused with . fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.