這個問題在這里已經有了答案: 如何在正則運算式中使用變數? (23 個回答) 3 天前關閉。
這個帖子3天前編輯過提交審核,重新打開帖子失敗:
原始關閉原因未解決
我正在嘗試計算字串“你今天好嗎?你真是個好人!我很少看到像你一樣好的人。
按照這個問題:計算字串 javascript 中的某些單詞
然而!我想添加單詞“are”作為變數。所以簡單的 '/\bare\b/g' 解決方案不起作用。
我已經解決了其他一些問題并進行了這次嘗試,但它似乎根本不起作用。我覺得我錯過了關于“patt”變數的一個難題。
var string = document.getElementById("text").innerHTML;
var term = 'are'
var patt = "/\b" term "\b/g"
var number = string.split(patt).length-1
console.log('string is: ' string)
console.log('term is: ' term)
console.log('regex is: ' patt)
console.log("there were " number " mentions of the term");
<p id=text >How are you doing today? You are such a nice person! I rarely see anybody as nice as you.</p>
uj5u.com熱心網友回復:
這是一個用字串串列過濾文本的函式
let blacklist = ["another", "any", "are"]
function filterText(text){
let digits = new RegExp(/\d /);
let words = new RegExp("\\b(" blacklist.join('|') ")\\b", "i")
let regex = new RegExp(digits.source "|" words.source, 'g');
return text.replace(regex, '');
}
uj5u.com熱心網友回復:
如果要使用字串構造正則運算式,則不能使用正則運算式文字,而是使用RegExp建構式:
var patt = new RegExp("\b" term "\b", "g")
uj5u.com熱心網友回復:
在回復的用戶的幫助下,我設法找到了混淆的真正原因
我需要使用新的 RegExp。
我需要使用 '//b' 而不是 '/b' 或 '/\b' 等。
patt 變數應該是: var patt = new RegExp("\b" term "\b", "g")
導致:
var string = document.getElementById("text").innerHTML;
var term = 'are'
var patt = new RegExp("\\b" term "\\b", "g")
var number = string.match(patt).length
console.log('string is: ' string)
console.log('term is: ' term)
console.log('regex is: ' patt)
console.log("there were " number " mentions of the term");
<p id=text >How are you doing today? You are such a nice person! I rarely see anybody as nice as you.</p>
正確識別完整變數詞的 2 次完整使用。(忽略“很少”)
我也將.split的用法更新為.match,謝謝!
uj5u.com熱心網友回復:
<script>
function countOccurrences(str,word)
{
var a = str.split(word);
return a.length-1;
}
let str = "portal portal portal portal GeeksforGeeks A computer science portal for geeks ";
let word = "portal";
console.log(countOccurrences(str, word));
</script>
o/p 5
uj5u.com熱心網友回復:
編輯:感謝@SGPascoe 提醒我添加\b正則運算式!
您不需要拆分字串來計數。
您可以簡單地使用match()并獲取其長度。
var string = "How are you doing today? You are such a nice person! I rarely see anybody as nice as you.";
var term = 'are';
var patt = new RegExp(`\\b${term}\\b`, "g"); // construct the regex
var number = string.match(patt).length; // retrieves the result of matching a string against a regular expression and get its length
console.log('string is: ' string);
console.log('term is: ' term);
console.log('regex is: ' patt);
console.log("there were " number " mentions of the string");
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401265.html
標籤:javascript 正则表达式
上一篇:替換R中字串末尾的點
下一篇:Perl5簽名:傳遞多個陣列
