JanLi
JanLi

Reputation: 71

how to remove title in img html

i have a html text like that i get from database, but it have a hover that show the image name, so i want to remove the title

from this

<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">

to this

<img title="" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">

i have tried

var text = '<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">'

text.replace(/(<img .*title=")(.+)(")/, '$1$3')

but it also remove my src "<img title="">"

any help guys ?

Upvotes: 0

Views: 891

Answers (4)

Praneeth Kumar
Praneeth Kumar

Reputation: 234

Simpler and cleaner way.

var xmlString = '<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">'

var x = new DOMParser().parseFromString(xmlString, "text/xml").documentElement
x.removeAttribute("title")
console.log(x)

Upvotes: 0

Peter B
Peter B

Reputation: 24202

It can be very hard, if not impossible, to reliably parse HTML using the likes of regex, indexOf, etc. The whole issue can be totally avoided by using the built-in DOMParser object, as follows:

const html = '<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">';
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const img = doc.body.children[0];
img.title = "";
console.log(img.outerHTML)

You could also use img.removeAttribute("title"); if you want to get totally rid of the title attribute.

Upvotes: 0

David Min
David Min

Reputation: 1414

If you are only getting the element as a string and not as a DOM element, then you can try using \"[\s\S]+(?= ) to select the portion of string that goes from the first " to the first space (returning you "AAAAAAA").

You can then replace the text as per your code in the question.

Upvotes: 0

MetropolisCZ
MetropolisCZ

Reputation: 605

You could use JS function removeAttribute():

document.getElementById("someId").removeAttribute("title");
console.log(document.getElementById("someId"));
<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212" id="someId">

EDIT: How to remove with regex

var text = '<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">';



console.log(text.replace(/ title=".[^"]*"/, ''))

How to remove only title´s value:

var text = '<img title="AAAAAAA" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" alt="" width="212" height="212">';



console.log(text.replace(/title=".[^"]*"/, 'title=""'))

Upvotes: 3

Related Questions