PatS
PatS

Reputation: 11434

javascript replace string after matching line

I expected to find an answer to a typical problem with regular expressions.

Many examples of how to use RegEx replace assume you know the pattern you want to replace. Great for teaching but not typical (IMO). See w3 schools and MDN. If it is on the MDN page please point it out.

In my latest problem, I have an html file that has uniq IDs on a line so I can perform this simple replacement. The syntax of the lines I need modified are shown below. I can place a unique string in the file so I can find the correct line to update.

<span id="lastModified">2018-10-26</span>
<span id="builtBy">Pat</span>

I need to find the line that has id="lastModified" and change the date.

I need to find the line that has id="builtBy" and change the date.

I tried a few different things. One is

var res = str.replace(/id="lastModified".*>(.*)<.span>/, newDate );

I thought the default might be to change the data matched in the parens (nope it doesn't work that way). See JSFiddle code example of what I tried that didn't work.

NOTE: In my case I'm trying to figure this out because for a simple string replacement using gulp-replace but it's really a javascript pattern matching and replacement problem so I'm not bring gulp-replace into this question other than to mention it.

NOTE: In my case, this code is not executing in the browser, so typical DOM manipulation will not work.

Other questions that I found (but didn't answer my question) were:

Upvotes: 1

Views: 1113

Answers (1)

Poul Bak
Poul Bak

Reputation: 10929

You can use this regex to match your first line:

/(<span id="lastModified">)(.*?)(</span>)/

It basically matches literally the text and captures it in three Groups, which is then used in the replacement pattern, which can be:

$12018-10-26$3

First it replaces with $1 (the first matched Group), then your date (which you will want to come from a variable) and finally $3 which is the end span.

Upvotes: 1

Related Questions