3

I have this text

var test = "<span data-toggle="tooltip" title="2Test">1TEST</span>";

I don't rely not sure what I am doing and could need some help. This is what I tried:

test = test.replace(/<span data-toggle="tooltip" title="|">[^>]*>/gi, "");

The test variable should only return the value inside of "title".

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

I agree with @Biffen you shouldn't really parse HTML with regex! But if you must do it, try this...

var test = "<span data-toggle='tooltip' title='2Test'>1TEST</span>";
var result = test.match(/title='([^']+)'/)[1];

console.log(result); //2Test
curv
  • 3,796
  • 4
  • 33
  • 48
  • This works fine but only if the variable 'test' contains "title" if "title" isn't there it trows an error. Like `var test = "normal text"`. But I will find a solution for that myself thanks a lot. –  Dec 19 '16 at 09:54
1

You don't need to parse HTML to get the title attribute, instead you can access title attribute from HTML DOM.

Create a temporary container with createElement, then set inner html with your html string, lastly traverse to first child which is the span and get the title attribute that you want.

Example:

var test = "<span data-toggle='tooltip' title='2Test'>1TEST</span>";

var el = document.createElement('div');
el.innerHTML = test;
var title = el.firstChild.getAttribute('title')
console.log(title) //2Test
alpha
  • 1,103
  • 7
  • 10