Search and Replace Words in HTML

前端 未结 3 1934
小蘑菇
小蘑菇 2021-02-18 14:24

what I\'m trying to do is make a \'jargon buster\'. Basically I have some html and some glossary terms in a database. When the person clicks on jargon buster it replaces the wor

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-18 14:40

    I had this problem in JS getting individual words. What I did was the following (you can translate it from JS to PHP):

    It actually works REALLY well for me. :)

    var words = document.body.innerHTML;
    
    // FIRST PASS
    
    // remove scripts
    words = words.replace(/[\s\S]*?<\/script>/gi, '');
    // remove CSS
    words = words.replace(/[\s\S]*?<\/style>/gi, '');
    // remove comments
    words = words.replace(//g, '');
    // remove html character entities
    words = words.replace(/&.*?;/g, ' ');
    // remove all HTML
    words = words.replace(/<[\s\S]*?>/g, '');
    
    // SECOND PASS
    
    // remove all newlines
    words = words.replace(/\n/g, ' ');
    // replace multiple spaces with 1 space
    words = words.replace(/\s{2,}/g, ' ');
    
    // split each word
    words = words.split(/[^a-z-']+/gi);
    

提交回复
热议问题