[英]Javascript: Remove words and words in brackets from array of strings
I am trying to remove unnecessary words from a string.我正在尝试从字符串中删除不必要的单词。 Like for example, "Finely chopped" or removing words in brackets like "(Optional)".例如,“切碎”或删除括号中的单词,如“(可选)”。 I have code that removes measurements but I am finding it difficult to get the desired output.我有删除测量值的代码,但我发现很难获得所需的输出。
Input:输入:
const Input = [
'chopped kale, or to taste',
'lemon, juiced',
'small yellow squash, diced (Optional)'
]
I am just trying to make regex that looks for words in an array called unwanted words like 'to taste' and , 'diced' and removes them我只是想让正则表达式在一个叫做“品尝”和“切块”等不需要的词的数组中查找词并删除它们
Desired Output:期望输出:
const output = [
'chopped kale',
'lemon',
'small yellow squash'
]
This is my code:这是我的代码:
import {measures} from './measures'
const regXMeasureAndMatter = RegExp('^(?<left>[^¼½¾\\d]+)*(?<count>¼|½|¾|\\d+\\/\\d+|\\d+)\\s*(?<unit>' + measures.join('|') + ')*(?<right>.*)');
function rearrangeMeasureAndMatter(match, left, count, unit, right) {
left = (left || '' ).trim();
right = (right || '' ).trim();
return [
count,
(unit || ''),
[left, right].join((left && right) || '')
].join(' ')
}
export function arrangeIngri(str) {
return str
.replace(regXMeasureAndMatter, rearrangeMeasureAndMatter)
.replace(/\s+/g, ' ').trim()
}
// get proper ingris
export function createUnitCentricCapturingRegX(unitList) {
const options = unitList
.map(unit => escapeRegExpSearchString(unit))
.join('|')
.replace((/\\\.\\s\+/g), '\\\.\\s*');
return RegExp('^(?<amount>.*?\\s*\\b(?:' + options + '))\\b\\s*(?<value>.*)$', 'i');
}
export const unitlessCapturingRegX = (/^(?<amount>¼|½|¾|\d+\/\d+|\d+)\s*(?<value>.*)$/);
export function collectNamedCaptureGroupData(collector, item) {
item = item.trim();
const { regXPrimary, regXSecondary, defaultKey, list } = collector;
const result = regXPrimary.exec(item) || regXSecondary.exec(item);
list.push(
(result && result.groups && Object.assign({}, result.groups))
|| { [defaultKey]: item }
);
return collector;
}
function escapeRegExpSearchString(text) {
return text
.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&')
.replace((/\s+/), '\\s+');
}
const splitMe = w => w.map(a => a.substr(0, a.lastIndexOf(",")))
const input = [
'chopped kale, or to taste',
'lemon, juiced',
'small yellow squash, diced (Optional)'
]
code spits out as expected代码按预期吐出
const output = [
'chopped kale',
'lemon',
'small yellow squash'
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.