admin管理员组

文章数量:1352788

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

i will try this way

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

u can try here /

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

i will try this way

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

u can try here http://jsfiddle/pw7Mb/

Share Improve this question asked Jul 26, 2012 at 6:16 SenderSender 6,85812 gold badges49 silver badges69 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

You would need to escape the slash in regex literals:

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

However, that could return null if nothing is found so you need to check for that:

var count = match ? match.length : 0;

A shorter version could use split, which returns the parts between the matches, always as an array:

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

Enter a regular expression using the escape character: (\)

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

本文标签: javascriptcount special characters from string in jqueryStack Overflow