2012-07-26 133 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);