Home > database >  Replace string pattern but keep part of it
Replace string pattern but keep part of it

Time:09-15

I have a long document with some headings I want to replace in a operation.

The headings have the following structure (there are two nouns, both in with a uppercase first character, separated with a whitespace, also the time is dynamic):

let string = 'Firstname Lastname [00:01:02]';

I want to insert some characters at the front and the end of this string, but want to keep the content.

So the desired output should be something like:

let string = '{Firstname Lastname [00:01:02]}:';

I tried a little bit around with RegEx and can catch the time with the following pattern:

\[[0-9]{2}:[0-9]{2}:[0-9]{2}

CodePudding user response:

You can use a template string to add characters to your final string; no need to try and mess with regular expressions

let a = "Firstname Lastname [00:01:02]" 
a = `{${a}}`

CodePudding user response:

I figured it out by using captures in my RegEx.

/(\b[A-Z][a-z]* [A-Z][a-z]*( [A-Z])?\b\s\[[0-9]{2}:[0-9]{2}:[0-9]{2}\])/g

This RegEx captures the pattern of my headings into group one. In a replace operation I can then insert the desired content.

string.replace(regex, '{$1}:')
  • Related