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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11663481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:56:44  来源:igfitidea点击:

count special characters from string in jquery

javascriptjquerystring

提问by Sender

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/

回答by Andrew Shepherd

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

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

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

回答by Bergi

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 nullif 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;