Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Replace all but what is inside of title=""

Tags:

javascript

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".


2 Answers

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
like image 91
curv Avatar answered Nov 30 '25 12:11

curv


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
like image 42
alpha Avatar answered Nov 30 '25 10:11

alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!