I'm attempting to delete everything but a matching pattern using javascripts .replace()
function and regex.
I want to save the digits from the "date" field, i.e 11 10 2021 or 9 10 2021. This regex /[\d]{1,2} [0-9]{2} [0-9]{4}/g
matches to the date patterns, however when using .replace(regex, '')
it replaces those digits rather than saving them. I'm just wondering how to "invert" the pattern to save the digits and replace everything else.
Example strings:
SURVEY API RESULT LANDING: [{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"11 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
[{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
CodePudding user response:
To find a single date, try the following
`[{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]`.replace(/.*([\d]{1,2} [0-9]{2} [0-9]{4}).*/gms, "$1");
RegExp reference https://javascript.info/regexp-introduction
CodePudding user response:
Use regex exec or string matchAll instead string replace
exec
const regex = /[\d]{1,2} [\d]{2} [\d]{4}/g;
const str = `SURVEY API RESULT LANDING: [{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"11 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
[{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]`;
let match;
while(match = regex.exec(str)) {
console.log(match[0]);
}
matchAll
const iterator = `SURVEY API RESULT LANDING: [{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"12 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
[{"_id":"616392e41a03eed562de2e8a",
"userId":"[email protected]",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]`.matchAll(/[\d]{1,2} [\d]{2} [\d]{4}/g);
console.log(Array.from(iterator).map(m => m[0]));