替换以分号结尾的行

时间:2018-03-28 19:15:41

标签: javascript regex

我想在JavaScript中将所有以分号void MainWindow::makePlot(){ // generate some data: QVector<double> x(101), y(101); // initialize with entries 0..100 for (int i=0; i<101; ++i) { x[i] = i/50.0 - 1; // x goes from -1 to 1 y[i] = x[i]*x[i]; // let's plot a quadratic function } // create graph and assign data to it: ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(x, y); // give the axes some labels: ui->customPlot->xAxis->setLabel("x"); ui->customPlot->yAxis->setLabel("y"); // set axes ranges, so we see all data: ui->customPlot->xAxis->setRange(-1, 1); ui->customPlot->yAxis->setRange(0, 1); ui->customPlot->replot(); double real_x = ui->customPlot->xAxis->coordToPixel(0) + ui->customPlot->x(); double real_y = ui->customPlot->yAxis->coordToPixel(0) + ui->customPlot->y(); QPoint real_cord(real_x, real_y); button->setGeometry(QRect(real_cord, QSize(20,20))); } 结尾的行替换为;

示例:

<li>$1</li>

会变成:

<p>one</p>
<p>two</p>
<p>three;</p>
<p>four;</p>
<p>five</p>

(我没有换行符,但是<p>one</p> <p>two</p> <li>three</li> <li>four</li> <p>five</p>

我试过这个正则表达式:

<p>first</p><p>second</p>etc.

但是来自第一个/<p>(.*?;)<\/p>/ 的匹配。

我还希望将它们包装在<p>中,但我认为这是超级先进的。

2 个答案:

答案 0 :(得分:0)

这里不需要正则表达式,只需遍历DOM元素并测试它们是否以;结尾。如果他们这样做,切掉它!

&#13;
&#13;
var p = document.getElementsByTagName('p')
for (var i = 0; i < p.length; i++) {
  if(p[i].textContent.endsWith(';')) {
    var x = document.createElement('li')
    x.textContent = p[i].textContent.slice(0,-1)
    p[i].parentNode.insertBefore(x,p[i])
    p[i].parentNode.removeChild(p[i])
    i--
  }
}
&#13;
<p>one</p>
<p>two</p>
<p>three;</p>
<p>four;</p>
<p>five</p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

不使用正则表达式,最好简单地使用适当的DOM操作方法 如果您需要较旧的浏览器支持,请参阅this question,了解如何替换for..of循环。

&#13;
&#13;
const nodes = document.querySelectorAll('p');
const matcher = new RegExp(';$');

for (const node of nodes) {
  if (!node.textContent.match(matcher)) continue;
  const newNode = document.createElement('li');
  newNode.textContent = node.textContent.replace(matcher, '');
  node.parentNode.replaceChild(newNode, node);
}
&#13;
<p>one</p>
<p>two</p>
<p>three;</p>
<p>four;</p>
<p>five</p>
&#13;
&#13;
&#13;