0

there is long string, like

<td>sdfaf</td><td width='1'></td><td width='1'>sdfdsf</td><td></td>

Is there a simple regex method to delete contents inside tags, convert it to

<td></td><td width='1'></td><td width='1'></td><td></td>

I know jquery html() and empty() can do the work, but I want to find a pure javascript method to do it.

thanks

2
  • I see you use the tag regex so I guess you thought it could be a good idea to try to use a regex to remove HTML content. I'll just let you read this. Commented Jan 16, 2013 at 20:31
  • thanks, I just wonder is there a regex replace method can do same work like preg_replace function in PHP. Commented Jan 17, 2013 at 4:50

3 Answers 3

3

Assuming your "string" comes from a table in your document, here's how to do it in vanilla javascript :

var cells = yourtable.getElementsByTagName('td');
for (var i=0; i<cells.length; i++) cells[i].innerHTML = '';

(if you just have the string, you may simply create a tr node and set this string as innerHTML)

Sign up to request clarification or add additional context in comments.

Comments

2

try this simple code

var tds = document.getElementsByTagName("td");

for ( var counter = 0; counter < tds.length; counter++ )
{
  tds[ counter ].innerHTML = ""; 
}

Comments

-1

Rough and ready, assuming no angle brackets between or inside the tags:

 str = str.replace( />[^<]+<\//g, '></' );

1 Comment

@user995789. Why have you accepted an answer that doesn't "use javascript replace" and which is not a "simple regex method"? Is it because of the high rep of the person that answered?

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.