簡體   English   中英

如何使用javascript或jquery找出一個單詞在一個文本區域中寫入了多少次

[英]how to find that how many times a specific word is written in one textarea using javascript or jquery

首先,我不擅長javascript或jquery,所以我想先在互聯網上搜索,就像我一直在做我不知道的事情一樣。 但是我找不到任何關於我的問題的信息,因此我想在這里尋求幫助,希望您能為我提供幫助。

當我開始提出問題時,該網站告訴我分享我的研究,但我沒有分享的內容。

我的問題是:“如何查找使用JavaScript或jquery在一個文本區域中寫入一個特定單詞多少次?”

我不確定這是否可以使用javascript或jquery完成,這就是為什么我同時編寫了這兩個文件的原因。

謝謝

一個簡單的概念證明:

$('#test').keyup(function(e){
    var v = $(this).val(), // the current value of the textarea,
        w = v.split(/\s/), // the individual words
        needle = 'img', // what you're looking for
        c = 0; // the count of that particular word
    for (var i=0,len=w.length;i<len;i++){
        // iterating over every word
        if (w[i] === needle){
        // if a given word is equal to the word you're looking for
        // increase the count variable by 1
            c++;
        }
    }
    // set the text of the 'output' element to be the count of occurrences
    $('#output').text(c);
});

JS小提琴演示

參考文獻:

您可以使用.match()匹配字符串中的正則表達式。

var str = "This my wordy string of words";
console.log(str.match(/word/g).length); // Prints 2 as it's matched wordy and words
console.log(str.match(/word\b/g).length); // Prints 0 as it has NOT matched wordy and words due to the word boundary

這些也區分大小寫。 您可能需要學習RegExp的其他選項。

嘗試

var regex = new RegExp('\\b' + word + '\\b', 'gi');
var count = string.match(regex).length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM