Javascript Regex to match only a single occurrence no more or less
You can do this
/^[^-]+-[^-]+$/
^
depicts the start of the string
$
depicts the end of the string
[^-]+
matches 1 to many characters except -
Weird (and not a Regex)... but why not?
2 === str.split("-").length;
/^[^-]*-[^-]*$/
Beginning of string, any number of non-hyphens, a hyphen, any number of non-hyphens, end of string.
You could use a combination of indexOf
and lastIndexOf
:
String.prototype.hasOne = function (character) {
var first = this.indexOf(character);
var last = this.lastIndexOf(character);
return first !== -1 &&
first === last;
};
'single-hyphen'.hasOne('-'); // true
'a-double-hyphen'.hasOne('-'); // first !== last, false
'nohyphen'.hasOne('-'); // first === -1, false
http://jsfiddle.net/cSF8T/