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/
您需要转义正则表达式文字中的斜杠:
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;
使用转义字符输入正则表达式:(\(
var count1 = temp1.match(///g);