-1

code:

<div id="start">    
    <p>"hi split html string"<p><br>"now"
    <img class="image1" src="some src" master_src="some src" master_w="400" master_h="320">
    "second tag is coming"<br><img class="image2" src="some src" master_src="some src" master_w="400" master_h="320"><h1>end here</h1>
</div>

output:

<p>"hi split html string"<p><br>"now" ,   "second tag is coming"<br> , <h1>end here</h1>

How can i achieve this ouput? what could be regex expression fot this image class in order to use split function(or any better way)?Please give me a demo

11
  • 1
    Smells like an XY problem... You probably want to use the DOM, not regex. Commented Jul 27, 2014 at 6:11
  • 1
    would you please give me a demo Commented Jul 27, 2014 at 6:12
  • since there can be any number of image tags so please give me some general solution Commented Jul 27, 2014 at 6:12
  • 1
    html.split(/<img[^>]*>/) Commented Jul 27, 2014 at 6:15
  • 1
    check this out: regex101.com/r/uT8aZ5/1 Commented Jul 27, 2014 at 6:27

2 Answers 2

1

why are you asking the same question multiple times?
Here is you answer

  $('#start').find('img').each(function(index){
    var split_text = $(this).html().split(/<img[^>]*>/)[index];
    alert(split_text);
  });
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not completely sure I understand your end goal, but if you want to remove the image from the HTML, you can use the DOM. First create a dummy element and set its innerHTML to the HTML string:

var dummy = document.createElement('div')
dummy.innerHTML = html

Now you got a div that contains your HTML structure as DOM elements. But, what you want is your div, not the dummy one:

var div = dummy.children[0]

Then loop the children, check if it's an image and remove it if so:

for (var i=0; i<div.children.length; i++) {
  var child = div.children[i]
  if (child.tagName == 'IMG') {
    div.removeChild(child)
  }
}

You can append the div to the DOM:

document.body.appendChild(div)

Or you can get back the HTML as a string and without the images:

div.innerHTML
//^ <p>"hi split html string"</p><br>"now""second tag is coming"<br><h1>end here</h1>

Also note that your HTML is not valid, you didn't close the paragraph with </p>, and so the above won't work if it isn't valid.

2 Comments

Couldn't you use outerHTML to skip a step?
@AustinMullins: Maybe, not sure what you mean, feel free to edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.