How to get only text from given HTML and Replace using Jquery?

爷,独闯天下 提交于 2020-01-22 02:21:28

问题


I need help in jquery. Thanks in advance.

I am using autocomplete function of jquery. There is a option for highlight. as like :-

highlight: function(match, keywords) {
            return match.replace(new RegExp("("+keywords+")", "gi"),'<b>$1</b>');
        }

It is working fine.. But i am getting result in HTML form. as like :-

<div id='22048,63' style='width:200px;text-align:left;'><div class='floatleft' style='width:165px'>(LAS) Las Vegas McCarran International Airport, Las Vegas, Nevada</div><div class='floatright' style='width:20px;padding-right:15px;'><img src='images/plane.gif' width='14' height='16' /></div></div>

Thats why if i enter in textbox "las" than it is replacing the class attribute from HTML and than my design has mashed up. Because "las" keyword is appearing in "Class". So it is replacing this.

I want only replace text that i got in HTML.

Than tell me there is any option in jquery so i can do this..

Thanks & Regards


回答1:


You can use .text() function to get just the text without the HTML Tags. Example:

function removeAllHtmlInsideDiv() {
    $(".example_1").html( $(".example_1").text() );
};
removeAllHtmlInsideDiv();

In your case, it can be used as:

highlight: function(match, keywords) {
    return (match.replace(new RegExp("("+keywords+")", "gi"),'<b>$1</b>')).text();
}

For Stripping HTML Tags from String:

function stripHTML(html)
{
    // var html = "<p>Some HTML</p>";
    var div = document.createElement("div");
    div.innerHTML = html;
    var text = div.textContent || div.innerText || "";
    return text;
}

So in your case, you need to put this way:

stripHTML(highlight);

Hope it helps! :)



来源:https://stackoverflow.com/questions/11095140/how-to-get-only-text-from-given-html-and-replace-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!