代码之家  ›  专栏  ›  技术社区  ›  sagarkothari

获取围绕特定标记的特定字符

  •  1
  • sagarkothari  · 技术社区  · 15 年前
    A simple tool to store and display texts longer than a few lines.
    The search button<div id="xyz">will highlight all</div> the words matching the name of objects that are members of the classes listed in searchedClasses, 
    itself a member of the KeySet class. The highlighted words are hypertext.
    

    我要检索被div xyz标记包围的字符。
    example output.
    ……搜索按钮 文字。。。。。

    我可以通过以下方式获得当前的div标签文本。

    function myDivHTML(valueName){
         if((obj = document.getElementById(valueName)) && obj != null){
            return obj.innerHTML;
         }      
    }
    

    我试过了 offsetParent

    我应该怎么做才能得到周围的文字?限制为10到20个字符。

    编辑:

    环绕文本表示->文本左侧10或20个字符,右侧10或20个字符。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Andy E    15 年前

    最简单的方法是,IMO将内部div的内容用两边模糊的字符串包装起来,然后在整个段落上使用正则表达式来查找添加的标记以及两边所需的字符数。像这样:

    var full, result,
        // textContent for w3 compliance, innerText for IE
        txt = "textContent" in document.body ? "textContent" : "innerText",
        // Get references to both divs and store the current text of `xyz`
        out = document.getElementById("outer"),
        xyz = document.getElementById("xyz"),
        old = xyz[txt];
    
    // wrap the inner text with something we can easily search for:
    xyz[txt] = "||||" + xyz[txt] + "||||";
    
    // Get the whole text, change the DOM text back to what it was
    full = out[txt];
    xyz[txt] = old;
    
    // Find the text with our markers and surrounding text:
    result = /.{0,10}\|{4}.*?\|{4}.{0,10}/.exec(full);
    
    alert(result[0]);
    // -> "ch button ||||will highlight all|||| the words"
    
    // Finally, replace your wrapping strings:
    result = result[0].replace(/\|{4}/g, "");
    
    alert(result);
    // -> "ch button will highlight all the words"
    

    您可能需要稍微调整regex,使其匹配,例如,内部字符串前后的两个整词。

    例子
    http://www.jsfiddle.net/Sy4rT/