0

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 ?

InSync
  • 4,851
  • 4
  • 8
  • 30
  • 1
    Which instances of "a" do you not consider to be an exact match to "a"? – Pointy Jun 11 '23 at 18:04
  • So this code will remove all a's in the string. What I need is to remove only an exact string of 'a'. So the result should have been [abc,bac] This is just an example as the point is to remove exact variable from the given string. – Gagik Manasyan Jun 11 '23 at 18:06
  • Surround `a` with `\b` then: `\ba\b`. – InSync Jun 11 '23 at 18:11
  • 1
    Maybe split the whole string into words first and then process the resulting array. – Pointy Jun 11 '23 at 18:14
  • Is it actually necessary to use only a single `split` for this? – Unmitigated Jun 11 '23 at 18:15
  • @InSync Is there a way to that with a variable ? Meaning make a exact match pattern regex with a given variable. – Gagik Manasyan Jun 11 '23 at 18:19
  • 1
    Use ```new RegExp(`\b${yourVariable}\b`)```. Do note that you need to escape special characters beforehand. – InSync Jun 11 '23 at 18:20
  • @InSync that won't work for split. – Gagik Manasyan Jun 11 '23 at 18:33
  • Why not? `String#split()` [accepts both strings and `RegExp` objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#parameters); in fact, it accepts anything that has a [`[Symbol.split]()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/split) method. – InSync Jun 11 '23 at 18:35
  • Was just about to post this when this post got closed. `let str = 'a abc a a bac of da van a'; let m = 'a'; let escUserRx = m.replace( /[\\$()*+\-.?\[\]^{|}]/g, '\\$&'); let Rx = new RegExp(\`(?:\\s+|^)${escUserRx}(?:\\s+${escUserRx})*(?:\\s+|$)\`); let result = str.split(Rx).filter(Boolean);; console.log(result);` I guess if it's not closed fast enough, somebody will post a better way to do it. – sln Jun 11 '23 at 19:47
  • Not really a duplicate. Just because something could be solved with a regex doesn't mean it should be. – knittl Jun 12 '23 at 19:04

2 Answers2

0

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);
knittl
  • 246,190
  • 53
  • 318
  • 364
0
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))