Sender
Sender

Reputation: 6858

count special characters from string in jquery

var temp = "/User/Create";
alert(temp.count("/")); //should output '2' find '/'

i will try this way

// the g in the regular expression says to search the whole string 
// rather than just find the first occurrence
// if u found User -> var count = temp.match(/User/g);
// But i find '/' char from string
var count = temp.match(///g);  
alert(count.length);

u can try here http://jsfiddle.net/pw7Mb/

Upvotes: 1

Views: 11834

Answers (2)

Bergi
Bergi

Reputation: 665070

You would need to escape the slash in regex literals:

var match = temp.match(/\//g);
// or
var match = temp.match(new RegExp("/", 'g'));

However, that could return null if nothing is found so you need to check for that:

var count = match ? match.length : 0;

A shorter version could use split, which returns the parts between the matches, always as an array:

var count = temp.split(/\//).length-1;
// or, without regex:
var count = temp.split("/").length-1;

Upvotes: 4

Andrew Shepherd
Andrew Shepherd

Reputation: 45262

Enter a regular expression using the escape character: (\)

var count1 = temp1.match(/\//g); 

Upvotes: 4

Related Questions