Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Replace 1st Instance of text

Tags:

jquery

If I have text like this;

<p>&nbsp;</p>
<p>this is the real text</p>
<p>&nbsp;</p>
<p>more</p>

What I need is a piece of jQuery that will replace the first instance only of <p>&nbsp;</p> with ''.

So the result after the call should be;

<p>this is the real text</p>
<p>&nbsp;</p>
<p>more</p>

But if the first line is not <p>&nbsp;</p> then the call should do nothing.

EDIT

I've tried implementing the solution from @Joey C. but I can't get it to work. The remove just doesn't.

var myHtml = "<p>abc</p><p>next para</p>";
var newElement = $(myHtml);

if ($(newElement).first("p").text() == "abc") {
    $(newElement).first("p").remove();
}

alert($(myHtml).text());
like image 778
griegs Avatar asked Jun 28 '10 01:06

griegs


People also ask

How to replace only first Occurrence of string in js?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.

How to replace DOM element jQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.


1 Answers

The following finds the first instance of a p element and removes it from the DOM if it's html is equal to "&nbsp;" like you specified.

   if ($("p:first").html() == "&nbsp;")  
     $("p:first").remove();

If the html is stored as a string in a variable, myHTML, you could create a DOM element and perform a similar comparison. In testing, I discovered that it works better if you wrap the elements you are creating with a div:

  var myHtml = "<p>abc</p><p>next para</p>";
  var newElement = $("<div>" + myHtml + "</div>");

  if (newElement).find("p:first").text() == "abc") {
     newElement.find("p:first").remove();
  }

  alert(newElement.html());

This will not actually update the string containing the original html code, so you must reassign it as well if you still need it in that variable.

  myHTML = newElement.html();
like image 59
Joey C. Avatar answered Oct 27 '22 05:10

Joey C.