【问题标题】:Javascript can't find strings containing square bracketsJavascript 找不到包含方括号的字符串
【发布时间】:2010-08-30 21:46:27
【问题描述】:

我正在使用这个功能来帮助我的网络开发人员在网页中找到一段代码:

function findString (str) {
  var strFound;
  strFound=self.find(str);
  if (strFound && self.getSelection && !self.getSelection().anchorNode ){   
    strFound=self.find(str);
  }
  if (!strFound) {
    strFound=self.find(str,1,1)
    while (self.find(str,1,1)) continue
  }
}

问题是当我输入以下字符串时:

array[1]

找不到!这很奇怪,因为我尝试了这个函数,它可以找到任何其他字符串。 那么,如何使用该函数查找包含方括号的字符串(如果可能,不使用正则表达式)?

谢谢,

问候

【问题讨论】:

    标签: javascript string square-bracket


    【解决方案1】:

    我试过你的脚本,但它有一个错误。如果您替换以下内容

    if (strFound && self.getSelection && !self.getSelection().anchorNode )  
    

    通过以下

    if (strFound && self.getSelection && !self.getSelection().anchorNode )  {
    

    它有效。

    在 Firefox 和 Chrome 中,当搜索字符串为数组 [1] 时,strFound 为真。 在 IE 8 中,脚本不起作用。

    编辑:我测试过的代码:

    $(document).ready(function() {
        findString("array[1]");
    });
    
    function findString (str) {
        var strFound;
        strFound=self.find(str);
        if (strFound && self.getSelection && !self.getSelection().anchorNode )  {
            strFound=self.find(str);
        }
        if (!strFound) {
            strFound=self.find(str,1,1)
            while (self.find(str,1,1)) continue
        }
        alert(strFound);
     }
    

    【讨论】:

    • 我编辑了这篇文章。我忘记了左括号,但即便如此,它也没有用。你能“粘贴”你的代码吗?谢谢。
    • 函数 findString (str) { var strFound; strFound=self.find(str); if (strFound && self.getSelection && !self.getSelection().anchorNode ) { strFound=self.find(str); } if (!strFound) { strFound=self.find(str,1,1) while (self.find(str,1,1)) continue } alert(strFound); } $(document).ready(function() { findString("array[1]"); });
    【解决方案2】:

    调用了什么对象函数find?那是窗户吗?是的,find 的功能到底是什么?根据文档,它是:

    find() 方法在调用时会显示一个查找对话框。 这允许用户在调用它的页面中搜索字符串。

    这是否意味着没有处理 HTML 令牌,而您正在寻找 HTML 令牌数组[1]?该功能支持哪些浏览器?

    实现服务器端搜索的一种方法是读取整个文件(假设您知道文件的位置)并使用字符串函数search做一个简单的正则表达式

    【讨论】:

    • 我使用的是 Firefox 3.6.8。你是对的,搜索功能很有帮助,但查找功能不仅可以找到字符串,还可以滚动到它并突出显示它。这就是为什么我试图让它与 find 功能一起工作。
    猜你喜欢
    • 2022-07-06
    • 2019-11-25
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多