簡體   English   中英

查找字符串jQuery / Javascript的部分

[英]Finding Parts of String jQuery/Javascript

問題

如何在字符串中找到一組特定的單詞(在這種情況下為gval)定義為特定的單詞集?

if(gval.indexOf("define") > -1){
    console.log("Yo! gval contains Define");
}
var gval = input.val().trim().toLowerCase();

謝謝!

如果要查找“單詞集”,則需要使用所需單詞Array ,然后利用jQuery庫提供的$ .inArray函數,可以嘗試以下操作:


現場演示: http //jsfiddle.net/t52aLmcz/

var text = 'this is a text that contains defined word', 
    textWords = text.split(' '), // create array of text words
    expectedWords = ['defined', 'this'], // expected words to be found
    word;

for (var i in textWords) {
    word = textWords[i];
    if($.inArray(word, expectedWords) != -1) {
        break; // if one of the expected words is found, do a break
    }
}

if (word) { // word exists
    console.log('Your text contains: ' + word);
}

也許您可以使用.split()解決問題。 制作一個包含所有單詞的數組。 循環遍歷以檢查單詞是否等於“ gval”。

<head>
</head>
<body>
    <h1 id=gval>In this sentence is a word gval and i want to find it! maybe more then once? gval gval</h1>
    <h2 id=outcome></h2>
    <script>
        var string = document.getElementById('gval').innerHTML; //create the string you want to check.
        var stringArray = string.split(' ');// Split the string every time it sees an space ' '.
        var ammount = 0;//This wil be the ammount of 'gval' there are in the sentence.
        for(i = 0; i < stringArray.length;i++){ // Loop through the length of the array.
            if(stringArray[i] == 'gval'){ // Check if the word is the same as 'gval'.
                ammount++;//If the word is the same as 'gval' increment ammount with +1.
            }
        }
        document.getElementById('outcome').innerHTML = ammount;//set the text in the H2 with id outcome to the ammount.
    </script>
</body>

如果要查找不區分大小寫的搜索,請使用此功能。 您首先需要設置變量gval,然后才可以檢查indexOf

var gval = input.val().trim().toLowerCase();
if(gval.indexOf("define") > -1){
console.log("Yo! gval contains Define");
}

暫無
暫無

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

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