/    Sign up×
Community /Pin to ProfileBookmark

js Regex to replace

tag with date string

Hi,everyone,
how to use js Regex to replace <p> tag with date string in the html?
**In fact, it is just add a class to date.**
old:

**<p>**2020-10-15</p>
**<p>**2020-10-26</p>
<p>aaa</p>

new:

**<p class=”date”>**2020-10-15</p>
**<p class=”date”>**2020-10-26</p>
<p>aaa</p>

**Bold is the changed part.**
I’m a js beginner, and I know the regex of date is `d{4}-d{2}-d{2}` ,
but how to write it completely in js?

Thank you all !

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumOct 27.2020 — I assume you intend to modify all p tags in the complete document? If so try this javascript:
&lt;script&gt;
document.querySelectorAll('p').forEach(item =&gt; {
if (item.textContent.match(/^d{4}-d{2}-d{2}$/)) {
item.classList.add('date');
}
});
&lt;/script&gt;
Place it at the end of the body, right before the closing `&lt;/body&gt;</C>.<br/>
It you want to make the replacement tolerant with leading and trailing whitespaces use this regex:<br/>
<C>
/^s?d{4}-d{2}-d{2}s?$/</C>

I further assumed that the p tag contains the date string <STRONG>**only**</STRONG>. If there may be other text around the date string, omit the ^ and $:<br/>
<C>
/s?d{4}-d{2}-d{2}/`
Copy linkTweet thisAlerts:
@Carson356authorOct 27.2020 — @Sempervivum#1624600 Thanks a lot. Perfect solution!
Copy linkTweet thisAlerts:
@VITSUSAOct 27.2020 — I agree with Sempervivum, this is a good solution :)
×

Success!

Help @Carson356 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.30,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...