js中判斷某字符串含有某字符出現的次數


str為某字符串

char為某字符

//得到字符串含有某個字符的個數  

function getCharCount(str,char){
var regex = new RegExp(char, 'g'); // 使用g表示整個字符串都要匹配
var result = str.match(regex);          //match方法可在字符串內檢索指定的值,或找到一個或多個正則表達式的匹配。
var count=!result ? 0 : result.length;
return count;
}

var count=getStrCount("abc,cde",'c');

count=2

Match()方法的語法

https://www.w3school.com.cn/jsref/jsref_match.asp

 

轉自:https://www.cnblogs.com/isxiaoming/p/12551473.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM