Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

[JavaScript] 特定の文字数をカウント

More than 5 years have passed since last update.

文字列中に特定の文字が何回出現するかを数える自作関数です。正規表現に変数を使えるよう、RegExp を利用します。

yotsuba_s.jpg サンプルコード

var all = "aaa\naaaa\nbbc";
alert(str_count(all, "\n")); // 2
alert(str_count(all, "aa")); // 3

// all の中に part が出現する回数を取得
function str_count(all, part) {
    return (all.match(new RegExp(part, "g")) || []).length;

yotsuba_s.jpg デモはこちら


(・o・ゞ いじょー。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away