2

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?

Nicc
  • 729
  • 3
  • 8
  • 18

3 Answers3

6

You've included ^ which matches the start of the string, and $ for the end. Your regex will only match strings comprised entirely of special characters.

cjol
  • 1,420
  • 10
  • 24
  • 3
    for the sake of completeness: `var specialChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/gi; ` – Alex Aug 24 '15 at 12:53
4

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);
Raghavendra
  • 3,341
  • 1
  • 16
  • 18
1

Try this:

/[@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g

Full code:

var sectionToCheck  = "$%klds$"; 
var allFoundCharacters = sectionToCheck.match(/[@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g);
alert(allFoundCharacters.length);//count
Manwal
  • 22,994
  • 11
  • 59
  • 91