簡體   English   中英

關於 Javascript 表達式的任何建議,以計算 Javascript 中特定字符串的出現次數

[英]Any suggestion on Javascript expression to count the number of occurrences of a particular string in Javascript

我們不是本地 Java/Javascript 程序員,但有時會從這些語言中獲得幫助來滿足我們的某些工作。 我們正在研究一些支持 XML-Javascript 表達式編寫的測試自動化工具。 我們有“驗證”選項來確認我們所需的字符串是否存在於輸入文件中。 我們通常使用 inputfile.indexOf('XYZ') 表達式來驗證輸入文件中是否存在 XYZ 字符串(此輸入文件只是文件中的字符數組,並且可以通過工具“驗證”選項輕松獲得。它包含一些我們知道的文件數據,您可以將其視為隨機文本文件)。 現在,我們的要求是檢查“abc”是否可用,如果可用,則“xyz”也應該可用。 最終,“abc”在輸入文件中出現的次數,“xyz”在輸入文件中也應該出現相同的次數。 在所有這些場景中,我的表達式的結果應該是 TRUE,否則應該始終是 FALSE。 關於如何在 javascript 中進行此類表達的任何建議?

您可以使用match並比較結果的長度。 就像是:

 const txt = `[**added demo abc] We are not native Java/Javascript programmers but sometimes get help from these languages to satisfy some of our job. We are working on some testing automation tool which supports XML-Javascript expression writing. There we have 'Verify' option to confirm if our required string is present in [**added demo abc] the input file or not. We usually use inputfile.indexOf('XYZ') expression to validate if XYZ string is present in the inputfile (this inputfile is just an array of characters from file, and is made readily available by tool to 'Verify' option. It contains some file data which we know, you can consider it as a random text file). Now, our requirement is to check if 'abc' is available and if it is available then 'xyz' should be also made available. Ultimately, the number of times 'abc' occurs in inputfile, same number of times 'xyz' also should be available in inputfile. In all these scenarios, my expression should result TRUE otherwise should always FALSE. Any suggestion on how to proceed for such expression in javascript?`; const matchLen = (str, re) => (str.match(re) || {length: 0}).length; console.log(`'abc' in txt and matches n of 'xyz' occurances in txt? ${ matchLen(txt, /abc/gi) > 0 && matchLen(txt, /abc/gi) === matchLen(txt, /xyz/gi)}`); console.log(`'expression' in txt and matches n of 'script' occurances in txt? ${ matchLen(txt, /expression/gi) > 0 && matchLen(txt, /expression/gi) === matchLen(txt, /script/gi)}`); console.log(`'nothingmatcheshere' in text and matches n of 'script' occurances in txt? ${ matchLen(txt, /nothingmatcheshere/gi) > 0 && matchLen(txt, /nothingmatcheshere/gi) === matchLen(txt, /script/gi)}`);

謝謝,太棒了,它對我有用...... 'abc' 和 'xyz' - 將表達式返回為 TRUE。 並且,當“abc”和“xyz”的計數不規則時不匹配依次返回 FALSE。

暫無
暫無

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

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