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

我会尝试这种方式

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

4

2 回答 2

4

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

var count1 = temp1.match(/\//g); 
于 2012-07-26T06:20:22.573 回答
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;
于 2012-07-26T07:00:11.463 回答