[英]count special characters from string in jquery
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.net/pw7Mb/ 您可以在这里尝试http://jsfiddle.net/pw7Mb/
使用转义符输入正则表达式:(\\)
var count1 = temp1.match(/\//g);
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: 但是,如果未找到任何内容,则可能返回null
,因此您需要检查以下内容:
var count = match ? match.length : 0;
A shorter version could use split
, which returns the parts between the matches, always as an array: 较短的版本可以使用split
,它总是以数组的形式返回匹配项之间的部分:
var count = temp.split(/\//).length-1;
// or, without regex:
var count = temp.split("/").length-1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.