3

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
  • 777
  • 3
  • 8
  • 19

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

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,530
  • 1
  • 17
  • 18
1

Try this:

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

Full code:

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