在javascript中通过子字符串和indexof删除标签和内容

Remove a tag and content of it by substring and indexof in javascript

本文关键字:indexof 删除 标签 字符串 javascript      更新时间:2023-09-26

我想转换这个:

<html>
s
<RB:Block_Left>sss</RB:Block_Left>
s
hello
</html>

,

<html>
s
s
hello
</html>

和这段代码必须在文本区这样我做了,但不能工作!

<textarea id ="code">
<html>
s
<RB:Block_Left>sss</RB:Block_Left>
s
hello
</html>
</textarea>
<br />
<input type="button" value="makeit!" onclick="ARAS()" />
<br />
<textarea id ="newcode">
</textarea>
<script>
function ARAS(){
    str=document.getElementById('code').value;
    str=str.substring(  + str.indexOf('<html>') - str.indexOf('<'/RB:Block_Left>') + str.indexOf('<'/RB:Block_Left>'));
    document.getElementById('newcode').value=str;
}
</script>

改变行:

str=str.substring(  + str.indexOf('<html>') - str.indexOf('<'/RB:Block_Left>') + str.indexOf('<'/RB:Block_Left>'));
str=str.substring(0,str.indexOf("<RB")-1) + str.substring(str.indexOf("/RB")+15)

你可以像处理HTML元素一样使用jQuery:

var ta = $("#code"); // Textarea
var tag = 'tag'; // Tag name or selector you want to remove
ta.val(
  $("<div>" + ta.val() + "</div>") // Wrap content of the textarea into a DIV tag
    .find(tag) // Find all the tags you want to remove
    .remove() // Remove them
    .end() // Get back the parent element
    .html() // Get HTML of the element
);
http://jsfiddle.net/w7Rkm/