Reputation: 21304
Maybe it's a simple question but today i'm a bit stucked with it.
I need regex to match only if symbol %
appeared once in a string..
for example:
/regexpForSymbol(%)/.test('50%') => true
/regexpForSymbol(%)/.test('50%%') => false
Thanks!
Upvotes: 12
Views: 20340
Reputation: 71548
You could use:
^[^%]*%[^%]*$
The anchors are there to ensure every character is covered, and you probably already know what [^%]
does.
Upvotes: 14
Reputation: 108500
You can use match
and count the resulting array:
str.match(/%/g).length == 1
Upvotes: 2
Reputation: 2553
Here you go. Don't expect everyone to make these for you all the time though.
^ # Start of string
[^%]* # Any number of a character not matching `%`, including none.
% # Matching exactly one `%`
[^%]* #
$ # End of string
Upvotes: 11
Reputation: 12042
You don't need regex.
function checkIfOne(string, char) {
return string.split(char).length === 2;
}
Usage:
var myString = "abcde%fgh",
check = checkIfOne(myString, '%'); // will be true
Upvotes: 2