简体   繁体   中英

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

    <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

for this i was using regex 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

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 ; after that

please suggest any solution

if you are using jquery you can pull out all span elements and replace innerHTML with them.

$("#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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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