从jquery中的字符串中计算特殊字符

时间:2012-07-26 06:16:23

标签: javascript jquery string

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/

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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;
相关问题