获取特定标记所包围的特定字符

时间:2010-07-21 10:01:04

标签: javascript html dom safari iphone

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属性 - 但是有很多可能,例如div标签可能在粗体标记和&amp;粗体标签可能位于p tag&amp;等等。

我该怎么做以获取周围的文字?限制可能是10,20个字符。

修改:

周围文字意味着 - &gt;文本左侧10或20个字符和右侧10或20个字符。

1 个答案:

答案 0 :(得分:2)

最简单的方法是,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"

您可能需要稍微调整正则表达式,以便匹配内部字符串之前和之后的两个完整单词。

  

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