Detect the html label on a string, get the value and delete the values ​​in the html tag in javascript

advertisements

I have a String which contains HTML tags:

var str = "Hello World <br><p>1</p><em>My First Javascript</em>";

And i also have a form with hidden input:

<input type='hidden' name='id' value=''>

With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.

Is there any way how to do this on Javascript or jquery?

Thanks guys!


So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -

var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);

Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -

var value = $holder.find('p').text(); // 1

Now that we have that value we can place it into the hidden input field -

$('input[name="id"]').val(value);

Now to remove all other elements from the original string - we'll use the container we created earlier for this -

$.each($holder.children(),function(index,elem){
  $(elem).remove();
});

Now we can take the textual contents of $holder with $holder.text() and it should be just -

Hello World


If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/