2

I know how to do this in php, but I need this to be done in javascript/jquery.

I'm trying to something like the following:

$('#NewBox').html( $('#OldBox').html().Replace('/<img(.*)alt="(.*)"\>/g', "$2") );

I don't think javascript has a preg_replace, and all I know of is the replace method. using "g" should replace all instances with the 2nd parameter from the regex (being alt). Any idea why this isn't working?

UPDATE: (hopefully this better understands what I want)

I have a string such as this:

var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image'

I want to replace all tags inside of that string with the alt so it's now:

'This is a string with logo an image'
MysteryDev
  • 610
  • 2
  • 12
  • 31

2 Answers2

8

Don't use regular expressions to manipulate HTML. Use DOM. That goes double when dealing in client side JavaScript as editing the HTML can break event handler binding.

Just get each image, loop over each of them, and replace with the value of the alt attribute.

$('img').each(function () {
  $(this).replaceWith(
    $(this).attr('alt')
  );
});
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

You should avoid regexes when you can safely work with a parsing tool. jQuery can parse that HTML for you.

var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image';
console.log('input: '+str);

// first create an element and add the string as its HTML
var container = $('<div>').html(str);

// then use .replaceWith(function()) to modify the HTML structure
container.find('img').replaceWith(function() { return this.alt; })

// finally get the HTML back as string
var strAlt = container.html();
console.log('output: '+strAlt);

Output:

input: This is a string with <img src="./images/logo.png" alt="logo" /> an image
output: This is a string with logo an image 

See demo fiddle.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • still not working but thanks anyway. I'll accept this as an answer. – MysteryDev Aug 08 '13 at 22:51
  • You don't have to accept it at all if it doesn't work. How is it not working? Did you try the demo? If you provide more details, we can help you further. – acdcjunior Aug 08 '13 at 22:54