Andan H M
Andan H M

Reputation: 793

JavaScript regular expression to extracting title content

I want to extract title form the input using regular expression

var str = '<a href="http://example/caraft.html" title="Queen Size">'; 
var pat = "title="([^"]+?)";
var result = str.match(pat);

Getting output like : title="Queen Size"

Output need : Queen Size

Temporarily I have achieved by using sub string

result = result.substring(6, (result.length-1));

I cannot figure a way to do it with regular expression.
Thanks in adavance

Upvotes: 2

Views: 572

Answers (3)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

var str = '<a href="http://example/caraft.html" title="Queen Size">',
    pat = 'title="([^"]+?)"',
    result = str.match(pat);

console.log(result[1]);

You have some problems with the quote character (") in your pattern. Furthermore str.match() returns an array containing the parentheses-captured matched results.

Alternatively you can use the Javascript regex syntax for your pattern:

var pat = /title="([^"]+?)"/;

Upvotes: 1

Aditya Singh
Aditya Singh

Reputation: 9612

Try this out:- https://jsfiddle.net/ombtkp6p/

jQuery(function($) {
  var str = '<a href="http://example/caraft.html" title="Queen Size">';
  var result = $(str).attr("title");
})

JavaScript Solution:-

var str = '<a href="http://example/caraft.html" title="Queen Size">'; 
var temp = document.createElement('div');
temp.innerHTML = str;
var htmlObject = temp.firstChild;
var result = htmlObject.getAttribute("title")

Upvotes: 1

Valery K.
Valery K.

Reputation: 147

If you need exactly regexp -- try this:

var str = '<a href="http://example/caraft.html" title="Queen Size">'; 
var pat = 'title="([^\"]+)?"';
var result = str.match(pat);

Upvotes: 1

Related Questions