There is a working regular expression in PHP /^(380|\\+380)\d{9}$/
How to write the same thing only in JavaScript?
There is a working regular expression in PHP /^(380|\\+380)\d{9}$/
How to write the same thing only in JavaScript?
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 ...
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/
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 ).
new RegExp() , then you need to put two backslashes instead of one because it takes a regular string as the first parameter. - Roman GrinyovYou can do the following:
var phone = "+380111122222"; res = phone.match( /^(380|\+380)\d{9}$/ ); console.log(res[0]); Source: https://ru.stackoverflow.com/questions/506921/
All Articles