如何用JavaScript提取字符串单词?实现移除括号外字符的代码方案
没问题,我来帮你搞定这两个JavaScript字符串处理的需求~
一、移除括号(含内容)以外的所有字符
针对你给出的示例,我们可以用正则表达式匹配所有带括号的内容,再把它们拼接起来就行,代码非常直观:
const string = "hello (hi) this (is) my (questions)"; // 全局匹配所有「(任意内容)」格式的片段,返回匹配结果数组 const bracketMatches = string.match(/\(.*?\)/g); // 把数组里的片段拼接成最终字符串,没匹配到的话返回空串 const result = bracketMatches ? bracketMatches.join('') : ''; console.log(result); // 输出:(hi)(is)(questions)
简单解释下正则/\(.*?\)/g:
\(和\):转义后匹配实际的左右括号(因为括号在正则里是特殊字符).*?:非贪婪模式匹配任意字符,这样会匹配到最近的右括号,避免把多个括号内容连在一起匹配g:全局匹配标志,会找出所有符合规则的片段
二、从字符串中提取指定单词
这里得看你说的「指定单词」具体是哪种情况,我给你列两种常见场景的实现:
场景1:提取精确匹配的某个单词
比如要提取字符串中所有独立的"hi",而不是包含"hi"的其他单词(比如"hihi"),可以用单词边界\b来确保匹配的是完整单词:
const str = "hello hi this is hi there hihi"; const targetWord = "hi"; // 动态生成正则,注意转义\b为\\b const regex = new RegExp(`\\b${targetWord}\\b`, 'g'); // 匹配结果,没找到的话返回空数组 const foundWords = str.match(regex) || []; console.log(foundWords); // 输出:["hi", "hi"]
场景2:提取符合特定模式的单词
比如提取所有括号里的单词(就是你示例里括号内的内容),或者提取长度大于3的单词,示例如下:
提取括号内的单词
const string = "hello (hi) this (is) my (questions)"; // 匹配括号内的内容,再去掉括号 const wordsInBrackets = string.match(/\((.*?)\)/g).map(item => item.slice(1, -1)); console.log(wordsInBrackets); // 输出:["hi", "is", "questions"]
提取长度≥4的单词
const str = "hello hi this is questions"; // 匹配长度至少4个字符的单词 const longWords = str.match(/\b\w{4,}\b/g) || []; console.log(longWords); // 输出:["hello", "this", "questions"]
内容的提问来源于stack exchange,提问作者PROPAR
相关产品推荐
相关产品推荐

