【问题标题】:Adjust index for HTML string to compensate for HTML tags调整 HTML 字符串的索引以补偿 HTML 标记
【发布时间】:2016-08-28 09:56:18
【问题描述】:

假设我有一个函数可以返回这个 HTML 字符串中单词“world”的起始索引 (4):

<div>The world is round</div>

这个函数(不在我的控制范围内)使用 jQuery 的.text() 方法工作。但是,我需要使用 jQuery 的 .html() 方法来完成我正在做的事情。

使用 jQuery 的 .html() 方法时,使用现有索引会给我跨度中的字母“n”。我需要更改此索引以考虑可能在 div 中的其他 HTML 标记和嵌套的 HTML 标记,例如

<div><p><span class="highlight">The</span></p> world is round</div>

因此,此代码 sn-p 将为 'world' 的第一个字母返回一个新的索引 42。我该怎么做呢?非常感谢!

更新:代码 sn-p 将返回包含标签的索引。我不想剥离标签。谢谢!

【问题讨论】:

  • 如果你有

    world

    世界是圆的
    ,函数应该返回什么?
  • 该函数应返回索引,包括 html 标记。所以,去掉标签,索引是4。当包括标签时,它是42。
  • 为什么不只是.html().indexOf("world")
  • 因为同一个词可能有多个实例,并且仅适用于第一个实例。

标签: javascript jquery html


【解决方案1】:
var result = sourceString.replace(/(<([^>]+)>)/ig,"").indexOf("word");

这是你需要的吗?以前的版本只提取第 n 个单词,但仔细阅读后,您似乎需要特定单词的索引,不包括标签,对吧?

【讨论】:

  • 抱歉,我需要索引包括标签。谢谢!
  • 所以,基本上你需要将返回索引4的函数的输出转换为包含html标签的上下文中相同单词的索引?
  • 是的。所以,在我的例子中,索引(不包括标签)是 4。当包括标签时,它是 42。42 是我需要的数字。谢谢!
  • 我还应该指出,一个给定的单词可能在一个字符串中出现多次。不确定这是否相关,因为我们按索引进行,但我想我还是会提到它:)
【解决方案2】:

我想出了一个解决方案,但它确实有一个警告......如果用户输入“”,它会失败。

        // Loop variables
        var within_html_tag = false;
        var tag_incrementer = 0;
        var text_incrementer = 0;
        var current_object_html = current_object.html();           

        // Adjust starting index to take account of HTML tags
        for (var i = 0; i < current_object_html.length; i++)
        {
            // Handle characters representing start or end of HTML tags
            if (current_object_html[i] == "<") { within_html_tag = true; }
            if (current_object_html[i] == ">") { within_html_tag = false; tag_incrementer++ }

            // Increment counters (depending on type)
            if (within_html_tag) { tag_incrementer++; } else { text_incrementer++; }

            // Once the desired index is reached, append tag incrementer and exit
            if (text_incrementer == start_index) 
            { 
                // Adjust the starting index
                start_index = text_incrementer + tag_incrementer;

                // Handle end of sentences
                if (current_object_html.substr((text_incrementer + tag_incrementer) - 2, 2) == "</") { start_index += 7; }

                // Escape procedure
                break; 
            }
        }

【讨论】:

    猜你喜欢
    • 2019-09-15
    • 2011-05-31
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2022-01-19
    • 2010-09-19
    相关资源
    最近更新 更多