最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Count special characters in a string - Stack Overflow

programmeradmin1浏览0评论

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
 |  Show 1 more ment

3 Answers 3

Reset to default 6

You'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

发布评论

评论列表(0)

  1. 暂无评论