skip to Main Content

Basically, I need to split a string to remove any exact matches.

Here’s what I tried.

let str = 'a abc a a bac';
let m = 'a';
str.split(m);

the result will remove all occurrences of the variable in the str. I need a way to put a variable inside a /^$/ regex to get only the exact matches. Any suggestions ?

2

Answers


  1. It sounds like you want to split your input into "words", then filter out some of the words. This can be achieved by using split followed by filter:

    const str = 'a abc a a bac';
    const m = 'a';
    const result = str.split(/s+/).filter(x => x != m);
    console.log(result);
    Login or Signup to reply.
  2. let str = 'a abc a a bac';
    //as you asked a to be in variable
    let m = 'a';
    //we need to form RegEx with variable
    //this expression matches a with word boundry and spaces if you wish to keep spaces just remove |\s 
    let reg = new RegExp('\b' + m + '\b|\s/gm')
    console.log(str.split(reg))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search