i have the following piece of code to count number of special characters in a string...somehow it does not return what i'd like
var sectionToCheck = $('input').val(); //it could be any kind of string entered in an input field such as "Hello @&% everybody"
var specialChars = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
var allFoundCharacters = sectionToCheck.match(specialChars);
console.log(allFoundCharacters);
It returns a null value for the variable allFoundCharacters. Any tips please?
i have the following piece of code to count number of special characters in a string...somehow it does not return what i'd like
var sectionToCheck = $('input').val(); //it could be any kind of string entered in an input field such as "Hello @&% everybody"
var specialChars = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
var allFoundCharacters = sectionToCheck.match(specialChars);
console.log(allFoundCharacters);
It returns a null value for the variable allFoundCharacters. Any tips please?
Share Improve this question edited Aug 24, 2015 at 12:53 Nicc asked Aug 24, 2015 at 12:46 NiccNicc 7773 gold badges8 silver badges19 bronze badges 6-
3
are we supposed to guess what
sectionToCheck
is? – Alex Commented Aug 24, 2015 at 12:47 - Could you edit your question and add a sample input ? – Aserre Commented Aug 24, 2015 at 12:48
- 1 possible duplicate of Count the number of occurences of a character in a string in Javascript – Tobias Golbs Commented Aug 24, 2015 at 12:48
- jsfiddle/pw7Mb/2 – Shailendra Sharma Commented Aug 24, 2015 at 12:48
- also, do you want to count the chars, strip them, want a string without special chars returned? – Alex Commented Aug 24, 2015 at 12:49
3 Answers
Reset to default 6You've included ^ which matches the start of the string, and $ for the end. Your regex will only match strings prised entirely of special characters.
Try this. Hope it will help you.
var str= "This is a string.";
// the g
in the regular expression says to search the whole string rather than just find the first occurrence
var count = (str.match(/is/g) || []).length;
alert(count);
Try this:
/[@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g
Full code:
var sectionToCheck = "$%klds$";
var allFoundCharacters = sectionToCheck.match(/[@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g);
alert(allFoundCharacters.length);//count