Javascript搜索问题

时间:2011-02-15 10:29:25

标签: javascript

我有一段代码在表格中搜索某个短语。找到短语后,它会将当前单元格的innerHTML返回到页面顶部附近的div。

我遇到的问题是:

除非被搜索的短语包含任何特殊字符(括号和&符号等),否则代码可以完美地运行。我尝试将短语从“Western & Central"修改为"Western & Central"但遗憾的是代码仍无法找到该短语。

下面是代码:

// Function for searching tables for specific map/device combination.
function findMap(map, device)
{
var flag = false;   // to check if the map has been found yet

// Add <strong> tags to map string so it is easier to search for
var mapstring = "<strong>" + map;
var map_regex = new RegExp( mapstring,'i');

// create array of tables
var tables = document.getElementsByTagName('table');

for (var t = 2; t < tables.length; t++)
{
    // create array of rows
    var tablerows = tables[t].rows;
    for (var r = 2; r < tablerows.length; r++)
    {
        currentRow = tablerows[r];

        // Check if current row contains map name
        if (currentRow.innerHTML.match(map_regex))
        {
            var tablecells = currentRow.cells;
            for (var c = 1; c < tablecells.length; c++)
            {
                currentCell = tablecells[c];
                // Check if current cell contains device name
                if (currentCell.innerHTML.match(device))
                {
                    document.getElementById("boxy2").innerHTML = currentCell.innerHTML;
                    flag = true;
                }
                if (flag == true) return; 
            }
            if (flag == true) return; 

            // search for x20 if 920 was not found etc
            if (device == "910")
                device = "x10";
            else if (device == "920")
                device = "x20";
            else if (device == "930")
                device = "x30";
            else if (device == "940")
                device = "x40";
            else if (device == "950")
                device = "x50";

            // search cells again
            for (var c = 1; c < tablecells.length; c++)
            {
                currentCell = tablecells[c];
                if (currentCell.innerHTML.match(device))
                {
                    document.getElementById("boxy2").innerHTML = currentCell.innerHTML;
                    flag = true;
                }
                if (flag == true) return;
            }
            if (flag == true) return;
        }
        if (flag == true) return; else  { document.getElementById("boxy2").innerHTML="Map not available on this device."; }
    }
}

}

非常感谢任何有关此事的帮助!

1 个答案:

答案 0 :(得分:2)

由于您只是想检查特定字符串是否存在,我认为如果您使用indexOf而不是RegExps,您的解决方案可能会更强大。

使用RegExps,如果您要查找特殊字符,例如[](),则需要将其转义,这只是另一层我觉得你不需要介绍的复杂性。

因此,请尝试替换正则表达式,例如......

if (currentRow.innerHTML.match(map_regex))

有了......

if (currentRow.innerHTML.indexOf(mapString)!=-1)