There is a working regular expression in PHP /^(380|\\+380)\d{9}$/

How to write the same thing only in JavaScript?

    2 answers 2

    The fact is that the + symbol is a service symbol of regular expressions ; therefore, to use it as a regular character, it must be escaped with a backslash ( \ ):

     /^(380|\+380)\d{9}$/ 

    Check it out ...


    1. At first, simply using the pattern attribute ...

    HTML:

     <form action="//google.com/search" target="_blank"> <input name="q" required pattern="(380|\+380)\d{9}"> <button>GO</button> </form> 

    Works: https://jsfiddle.net/q8wt17y3/


    1. Now, for reliability, and through JavaScript ...

    HTML:

     <form action="//google.com/search" target="_blank"> <input name="q"> <button>GO</button> </form> 

    Javascript:

     document.forms[0].onsubmit = function () { if ( !this.q.value.match( /^(380|\+380)\d{9}$/ ) ) { alert('No match with pattern!'); return false; } }; 

    Works: https://jsfiddle.net/4cfko1gq/


    By the way, in the HTML-attribute of pattern designation of the beginning ( ^ ) and end of the data ( $ ) can be omitted, since they are set by default. But in Javascript they are needed if you want to mark the beginning and / or end of the data.


    Also note that if you create a regular expression using the new RegExp() constructor, then instead of one backslash ( \ ), you need to specify two ( \\ ).

    The fact is that the constructor new RegExp() takes as its first parameter a regular string; and to put a backslash on a line, it needs to be screened; This is due to the fact that when the interpreter finds a backslash in a string, it thinks that it is a screened sequence (for example, the newline is \n ).

    • Something is not displayed code, where is "GO"? .. I do not understand why. - Roman Grinyov
    • Thanks, it was necessary to add "\\" before "+", and I had "\" - Vitaliy Fesyura
    • @ w3lifer wrote in the chat moderators about the problem. - Alex
    • @VitaliyFesyura, if you create a regular expression using the constructor new RegExp() , then you need to put two backslashes instead of one because it takes a regular string as the first parameter. - Roman Grinyov
    • Thanks a lot, it works: var reg = new RegExp ("(380 | \\ + 380) \\ d {9}"); I understand that ^ and $ in Java is not necessary. - Vitaliy Fesyura

    You can do the following:

     var phone = "+380111122222"; res = phone.match( /^(380|\+380)\d{9}$/ ); console.log(res[0]); 
    • Uncaught SyntaxError: Invalid regular expression: // ^ (380 | \ +380) d {9} $ / i /: Nothing to repeat - Vitaly Fesyura
    • one
      For some reason, you have the screening of y + missing and unnecessary borders of the regular expression. - cheops
    • Nadr was just to add "\\" - Vitaliy Fesyura