2012-07-26 94 views
1
var temp = "/User/Create"; 
alert(temp.count("/")); //should output '2' find '/' 

我会尝试这种方式计特殊字符jQuery中

// 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); 

ü可以尝试这里http://jsfiddle.net/pw7Mb/

+1

http://jsfiddle.net/pw7Mb/2/ – Imdad 2012-07-26 06:26:25

回答

4

您需要在正则表达式文字中跳过斜线:

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

但是,如果没有被发现,可以返回null所以你需要检查的是:

var count = match ? match.length : 0; 

一个较短的版本可以使用split,它返回匹配的部分,总是作为阵列:

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

输入一个正则表达式使用转义字符(\)

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