Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Replace everything except a matching pattern in regex

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@gmail.com",
"date":"11 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
    
[{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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@gmail.com",
"date":"11 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
    
[{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"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@gmail.com",
"date":"12 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
    
[{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"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]));

about 4 years ago · Juan Pablo Isaza Report

0

To find a single date, try the following

`[{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!