Home > Software design >  Adding a variable in the middle of a regex split?
Adding a variable in the middle of a regex split?

Time:12-30

I'm trying to count how many times 'are' is mentioned in the string 'How are you doing today? You are such a nice person! I rarely see anybody as nice as you.'

Following this question: Count certain words in string javascript

HOWEVER! I want to add the word 'are' as a variable. so the simple '/\bare\b/g' solution doesn't work.

I've worked from a few other questions and arrived at this attempt, but it doesn't seem to work at all. I feel I am missing a peice of the puzzle regarding the 'patt' variable.

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 string");
<p id=text >How are you doing today? You are such a nice person! I rarely see anybody as nice as you.</p>

CodePudding user response:

Heres a function to filter text with list of strings

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, '');
}

CodePudding user response:

If you want to construct a regex with a string, you can't use a regex literal, instead use the RegExp constructor:

var patt = new RegExp("\b" term "\b", "g")
  • Related