Javascript strip using regex to get before and after an a tag in string

Viewed 42

I have this string from the server

15 Steps is mandatory and must be completed by 14/02/2021: click <a href='http://example.co.uk/training/CRU0007'>here</a> to book/start your learning.

I need to get 2 values

 15 Steps is mandatory and must be completed by 14/02/2021: click 

&

 to book/start your learning.

When I tried this before I had a string wrapped in : and ; and the below code worked

var arrStr = newsText.split(/[:;]/);

but if I try

var arrStr = newsText.split(/[<a></a>]/);

I get a jumbled mess.

So I decided to try and use regex and got this far

const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;
var arrStr = newsText.split(linkRx);

But this leaves the >here</a> in the final part

So how do I edit the regex to get the rest of the a tag. I've searched through lots of answers but they don't seem to get the whole tag.

2 Answers

I would use the following regex.

The purpose is to get wathever is before and after the <anything></anything>.

const str = `15 Steps is mandatory and must be completed by 14/02/2021: click <a href='http://example.co.uk/training/CRU0007'>here</a> to book/start your learning.`;

const regex = /(.*?)(?:<.*?>.*?<\/.*?>)(.*)/gm;

const [,
  partA,
  partB,
] = regex.exec(str);

console.log('PartA :', partA);
console.log('PartB :', partB);


enter image description here

Based on your attempt, could you please try following, Online demo is: Online regex demo

var newsText = `15 Steps is mandatory and must be completed by 14/02/2021: click <a href='http://example.co.uk/training/CRU0007'>here</a> to book/start your learning.`

var arrStr = newsText.split(/\s*<a\s+href=[^>]*>[^>]*<\/a>\s*/);

console.log(arrStr);

Explanation: if matches 0+ whitespaces followed by a <href= tag and closing </a> tag followed by 0+ whitespaces.

Related