英文:
How can I split a string with an exact match of a variable?
问题
我需要将字符串分割以移除任何精确匹配。
这是我尝试过的。
let str = 'a abc a a bac';
let m = 'a';
str.split(m);
结果将移除字符串中所有变量的出现。我需要一种方法将变量放入 /^$/ 正则表达式中,以仅获取精确匹配。有什么建议吗?
英文:
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 ?
答案1
得分: 0
这听起来像是您想要将输入分割为“单词”,然后筛选掉其中的一些单词。这可以通过使用split
然后使用filter
来实现:
const str = 'a abc a a bac';
const m = 'a';
const result = str.split(/\s+/).filter(x => x != m);
console.log(result);
英文:
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
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = 'a abc a a bac';
const m = 'a';
const result = str.split(/\s+/).filter(x => x != m);
console.log(result);
<!-- end snippet -->
答案2
得分: 0
let str = 'a abc a a bac';
//根据您的要求将a存储在变量中
let m = 'a';
//我们需要使用变量形成正则表达式
//这个表达式匹配a与单词边界和空格,如果您想保留空格,只需删除|\s
let reg = new RegExp('\b' + m + '\b|\s', 'gm');
console.log(str.split(reg))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论