2015-12-14 87 views
3

我想分割一个字符串并使用JavaScipt函数替换 字符串中的一个字符。我的功能如下..在JavaScript函数中分割和替换

<script> 
function test(table, col) { 
    var table = document.getElementById(table); 
    for (x = 1; x < table.rows.length; x++) { 
     var temp = table.rows[x].cells[col].innerHTML; 
     table.rows[x].cells[col].innerHTML = .replace('P', 'B'); 
    } 
} 
</script> 

所以它传递以下字符串http://ff00.00--p.yos.local:3042/htmltemps/newtest.html和 我期待这样的结果:http://ff00.00--b.yos.local:3042/htmltemps/newtest.html。但我得到这个: b/htmltemps/newtest.html。任何帮助都会被处理。

+0

它应该是'temp.replace('P','B')'。 –

回答

0
var str = "http://ff00.00--p.yos.local:3042/htmltemps/newtest.html"; 
var res = str.replace("--p", "--b"); 

注意:没有必要使用split()。

0

将RegExo对象与不区分大小写的标志i一起使用。

function replaceTexts(tableId, columnIndex) { 
 
    var table = document.getElementById(tableId); 
 
    Array.prototype.forEach.call(table.rows, function(row) { 
 
    var cell = row.cells[columnIndex]; 
 
    cell.innerHTML = cell.innerHTML.replace(new RegExp("P", "gim"), 'b'); 
 
    }); 
 
} 
 

 
replaceTexts('table', 0);
<table id="table"> 
 
    <tr> 
 
    <td> 
 
     http://ff00.00--p.yos.local:3042/htmltemps/newtest.html 
 
    </td> 
 
    <td> 
 
     http://ff00.02--p.yos.local:3042/htmltemps/newtest2.html 
 
    </td> 
 
    </tr> 
 
    </table>

还要注意pHTTP被替换。这可能是不希望的,所以我建议你删除方案部分(http)。