I have an array of strings. i am using regular i am trying to find index of occurrence of element and remove substring from string but i have problem when i add another occurrence of character
My solution:
const names = [
'COMMENT — CODE | COUNTRY | DATE | TARGET',
'CODE| COUNTRY | DATE |TARGET',
'CODE|| COUNTRY| DATE |TARGET',
'COMMENT 1 — COMMENT 2 — CODE | COUNTRY | DATE | TARGET',
];
const exp = new RegExp(/—|-/);
const filteredNames = names.map(name => {
const index = name.match(exp)?.index;
return name.slice(index 1)
});
My result:
"CODE | COUNTRY | DATE | TARGET"
"CODE| COUNTRY | DATE |TARGET"
"CODE|| COUNTRY| DATE |TARGET"
"COMMENT 2 — CODE | COUNTRY | DATE | TARGET" <- not correct
But expected result:
"CODE | COUNTRY | DATE | TARGET"
"CODE| COUNTRY | DATE |TARGET"
"CODE|| COUNTRY| DATE |TARGET"
"CODE | COUNTRY | DATE | TARGET"
I shall be most grateful for any help in this matter.
CodePudding user response:
You can just select part which you need:
const names = [
'COMMENT — CODE | COUNTRY | DATE | TARGET',
'CODE| COUNTRY | DATE |TARGET',
'CODE|| COUNTRY| DATE |TARGET',
'COMMENT 1 — COMMENT 2 — CODE | COUNTRY | DATE | TARGET',
];
const exp = new RegExp(/(\w (\s*\|*\s*))*\w \s*$/g);
const filteredNames = names.map(name => {
const matches = name.match(exp);
return matches?.[0] || '';
});
console.log(filteredNames);
CodePudding user response:
We could try a regex replacement approach here:
var names = [
'COMMENT — CODE | COUNTRY | DATE | TARGET',
'CODE| COUNTRY | DATE |TARGET',
'CODE|| COUNTRY| DATE |TARGET',
'COMMENT 1 — COMMENT 2 — CODE | COUNTRY | DATE | TARGET',
];
var output = names.map(x => x.replace(/(?:.*? — )*([^ |] )/g, "$1"));
console.log(output);
Here is an explanation of the regex pattern being used here:
(?:.*? — )* match (but do not capture) a "TERM — ", zero or more times
([^ |] ) then capture the final term in $1
Then, we replace each pipe delimited entry with $1
, the final term.