简体   繁体   English

正则表达式替换div的内部html中的字符串

[英]regex to replace a string from the inner html of a div

i have a div that contains some html and text (html is added dynamically)the structure would be like 我有一个包含一些html和文本的div(html是动态添加的)结构类似于

    <div id="contentContainer">
&nbsp; <span>ProductA</span> ; <span>ProductB</span>; prod
</div> 

i want to remove the last incomplete text (prod) from the inner html of the div contentContainer on submit button click 我想从提交按钮上的div contentContainer的内部html中删除最后一个不完整的文本(prod)

for this i was using regex returnText.replace(/\\w+$/, ''); 为此,我正在使用正则表达式returnText.replace(/ \\ w + $ /,''); and it works fine as i can not trim the text to last index of ';' 并且它可以正常工作,因为我无法将文本修剪到最后一个索引“;”

but not the issue is when user puts some special charaters in the incomplete text as pr\\od the regex fails 但是问题不在于当用户在pr \\ od上将某些特殊字符放在不完整的文本中时,正则表达式失败

so is there any solution to trim the last appended text the inner html of the div or can i trim the text to the last html tag and place ; 所以有什么解决方案可以将div的最后html修剪为最后添加的文本,或者可以将文本修剪为最后的html标签并放置? after that 之后

please suggest any solution 请提出任何解决方案

if you are using jquery you can pull out all span elements and replace innerHTML with them. 如果您使用的是jquery,则可以提取所有span元素并用它们替换innerHTML。

$("#contentContainer").html( $("#contentContainer span") );

That should clean rest things. 那应该清理休息的东西。 Maybe not the best but i think its better then regexp on content. 也许不是最好的,但我认为它比内容的正则表达式更好。

Solution looks at the last DOM node in DIV, if it is a text node it changes text to semi-colon 解决方案查看DIV中的最后一个DOM节点,如果它是文本节点,则将文本更改为分号

var lastNode = $('#contentContainer').contents().last()[0]

if (lastNode.nodeType == 3) {
    lastNode.textContent=';'
}

demo: http://jsfiddle.net/EhcLh/ 演示: http : //jsfiddle.net/EhcLh/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM