【问题标题】:javascript compatibility chrome, safari, and opera on string searchjavascript 兼容性 chrome、safari 和opera 在字符串搜索上
【发布时间】:2014-12-13 19:31:56
【问题描述】:

我正在做我的第一个 javascript 应用程序,我注意到它只适用于 firefox(我无法测试 IE)。 我创建这个软件只是为了做一些练习,简单地说,它允许在给定文本中搜索给定单词,并在 div 块上呈现,原始文本突出显示搜索的单词(如果存在)并告诉找到该词的次数。

变量string是要搜索的文本,变量target是要搜索的词,变量result 是存储在 string 中的搜索结果的位置。

我遇到的问题是,虽然在 Firefox 中代码可以完美地找到文本中每次存在的单词,但在其他浏览器中(基于 webkit?)它只能找到一次单词。 em>

这是 JavaScript 代码:

function wordFinder() {
    'use strict';
    var string = document.getElementById('paste').value,
        target = document.getElementById('target').value,
        result =  string.match(target, 'g'),
        marked = string.replace(target, '<span class="found">' + target + '</span>', 'g');
    if (result === null) {
        document.getElementById('result').innerHTML = 'Your word was not found in the content';
        document.getElementById('string').innerHTML = '<h2 align="center">No results to display</h2>';
    } else {
        document.getElementById('result').innerHTML = ('The word ' + target + ' was found ' + result.length + ' times.');
        document.getElementById('string').innerHTML = marked;
    }
}

这是 HTML:

    <!DOCTYPE html>

<html>
<head>
    <title>Page Title</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <script src="script.js" type="text/javascript" language="javascript"></script>
</head>
<body>
    <h2>Word finder</h2>
    <form name="finder" action="wordFinder" method="post">
        Paste the text you want to search within:<br>
        <textarea name="text" rows="10" cols="100" id="paste"></textarea><br>
        Paste the word you want to search:<br>
        <input name="search" type="text" id="target"/>
        <br><button type="button" onclick="wordFinder()">Search.</button>
    </form>
    <h4 id="result"></h4>
    <div id="style" class="layout"><p id="string">Results will appear here</p></div>
</body>
</html>

提前感谢您的帮助

【问题讨论】:

    标签: javascript google-chrome firefox safari opera


    【解决方案1】:

    这一行的处理方式不同:

    result = string.match(target, 'g'),
    

    请注意,string.match 采用单个 RegExp 参数(请参阅ES5.1 spec)。您传递了两个参数,这意味着第一个被视为正则表达式,这意味着它不会为您提供全局匹配,除非target 类似于/foo/g。您可以自己创建RegExp 对象以使其全局匹配:

    result = string.match(new RegExp(target, 'g')),
    

    fiddle

    我测试了 Opera 12 (presto)、Opera 26、IE11 和 Chrome 40,它们的行为方式都相同,为您的原始代码提供了一个匹配项,只有 Firefox 的行为不同——似乎违反了 EcmaScript 5.1 规范。

    【讨论】:

    • 嗨,谢谢,现在可以了。我只有一个问题(因为这个概念对我来说还不是很清楚)。具有“found”类的跨度仅适用于第一个单词,其余的不标记。 :)
    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多