gpt4 book ai didi

javascript - 在jquery中计算字符串中的特殊字符

转载 作者:行者123 更新时间:2023-11-30 07:26:46 24 4
gpt4 key购买 nike

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/

最佳答案

您需要转义正则表达式中的斜线:

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;

关于javascript - 在jquery中计算字符串中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11663481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com