JavaScript函数中的拆分和替换

Splitting and replacing in a JavaScript function

本文关键字:替换 拆分 函数 JavaScript      更新时间:2023-09-26

我试图拆分一个字符串,并只替换使用JavaScipt函数的字符串。我的功能如下。。

<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。任何帮助都将不胜感激。

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

注意:不需要使用split()。

使用带有不区分大小写标志i的RegExo对象。

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>

还要注意,http中的p被替换。这可能是不需要的,所以我建议您删除scheme部分(http)。