How to match specific length of occurrences in RegEx/JavaScript? -
i have following variable:
var arg = '--test';
the value of arg
can start 1 or 2 hypens: -
or --
, not more.
i want handle , figured should regex problem.
so far, code is:
if(arg.substr(0, 2).match(/-{1,2}/gi)) { // doing stuff here... }
what slice first 2 characters of string , try test hypen occourence in sliced string, regex not strong side that's i'm stuck.
basically, want test if there's @ least 1 or maximum 2 -
hypens in string/argument.
you can restrict number of hyphens (?!-)
negative lookahead after ^-{1,2}
:
/^-{1,2}(?!-)/
see regex demo
pattern breakdown:
^
- start of string-{1,2}
- 1 or 2 hyphens(?!-)
- fail match if there hyphen after 2 hyphens @ start.
note check if regex matches given string or not in js, you'd better use regexp#test()
method, see demo below.
function tst() { var arg = document.getelementbyid("test").value; if (/^-{1,2}(?!-)/.test(arg)) { // <======== check if string matches pattern document.getelementbyid("res").innerhtml = arg + " matched"; } else { document.getelementbyid("res").innerhtml = arg + " failed match"; } }
<form> <input id="test" value="---test" placeholder="<input test string>"/> <input type="submit" onclick="tst()" id="r"/> <div id="res"/> </form>
Comments
Post a Comment