1

I have string with some links like below,

Some text will come here <a class="checkSomething" href="https://something.com" style="color: rgb(255, 255, 255); font-size: 17px;">Check Status</a>. Some text will come here <a href="#">Click</a> Some text will come here.

From the above string I want extract the href value where class name is checkSomething.

Basically I have to get the link alone, that is https://something.com

I tried the below regex

/<a class="checkSomething" href="([^"]*)">/

But it gives link with <a> tag like below

<a class="checkSomething" href="https://something.com"

Can someone help me on this? Thanks in advance!

Raja
  • 167
  • 1
  • 10

3 Answers3

1

You can't reliably parse HTML with a regular expression, so don't. You can however use the host's built–in parser, then get the A elements and return the value of the href attribute for those that have it.

Not all A elements are links, some are anchors so don't have href attributes. In that case, getAttribute will return null which (being falsey) filter will not add to the returned array.

var s = 'Some text will come here <a class="checkSomething" href="https://something.com" style="color: rgb(255, 255, 255); font-size: 17px;">Check Status</a>. Some text will come here <a href="#">Click</a> Some text will come here.'

function getHREFs(markup) {
  var el = document.createElement('div');
  el.innerHTML = markup;
  return Array.prototype.filter.call(el.querySelectorAll('a'), function(a) {
    return a.getAttribute('href');
  })
}

document.write(getHREFs(s));
RobG
  • 142,382
  • 31
  • 172
  • 209
1

I have no idea you are using browser or Node.js.

For Node.js

Code need cheerio module to work which is really recommend when process DOM with js.

'use strict';
const str = 'Some text will come here <a class="checkSomething" href="https://something.com" style="color: rgb(255, 255, 255); font-size: 17px;">Check Status</a>. Some text will come here <a href="#">Click</a> Some text will come here.';
const cheerio = require("cheerio");
const $ = cheerio.load(str);
$('a.checkSomething').each(function() {
  console.info($(this).attr('href'));
});

Link to this: https://tonicdev.com/56d349553836000d00e1452f/57044ede2d5c971100488733

For Browser

Someone already did.

SCLeo
  • 353
  • 3
  • 14
0

Try this:

/class="checkStatusNowLink" href="([^"]+)/

Online Demo

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89