javascript - 匹配标签内的部分文本

标签 javascript jquery html regex

我处于客户端上下文中。 我有这个html:

<p>Text text \n other text </p>

我只想匹配段落内的\n 元素,并仅将其替换为“br”标记。

我只想在标签“p”内和所有匹配中执行此操作。

我应该在 javascript 中使用正则表达式

感谢并为我糟糕的英语感到抱歉。

最佳答案

使用html()具有回调和内部回调的方法使用 String#replace 替换文本方法。

$('p').html(function(i, htm) {
  return htm.replace(/\\n/g, '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text text \n other text</p>

更新1:如果它是一个字符串,则使用 String#replace方法。

console.log(
  '<p>Text text \n other text</p>'.replace(/\n/g, '<br>')
)


更新 2: 如果字符串包含其他标记元素,并且您只想更新 p 标记,则执行类似操作。

var str = '<p>Text text \n other text</p>';

console.log(
  // create a temporary div eleemnt 
  $('<div>', {
    // set html content from string
    html: str
  })
  // get all p tags
  .find('p')
  // iterate and replace \n
  .html(function(i, htm) {
    // replace \n with br tag
    return htm.replace(/\n/g, '<br>')
  })
  // back to the temp div
  .end()
  // get it's updated html content
  .html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


更新 3:通过生成临时 DOM 元素使用纯 JavaScript。

var str = '<p>Text text \n other text</p>';
// create a temporary div element
var div = document.createElement('div');
// set html content form string
div.innerHTML = str;
// get all p tags and convert into Array using Array.from
// for older browser use [].sclice.call instead
Array.from(div.getElementsByTagName('p'))
  // iterate over p tags
  .forEach(function(el) {
    // update the html content
    el.innerHTML = el.innerHTML.replace(/\n/g, '<br>')
  });
// get updated html content
console.log(div.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 匹配标签内的部分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207078/

相关文章:

javascript - Jquery 搜索常见问题解答 - 稍作修改

html - 如何为 Google 的 AMP 页面格式插入闪电符号?

javascript - 将数据从 chrome 扩展程序传递到网页

javascript - JMVC : steal/buildjs - Build is throwing error "failed to open file file:/profile/getPolicy

jquery - 使用 jQuery 克隆在表单输入字段的多维数组中递增键

jquery - 如何编辑 "required"属性,并从 jquery 设置它

php - 如何使用我的php变量UserNameID删除数据库中用户的行

javascript - Class.prototype.Function() 与 Class.a Function()

javascript - 使用 SignalR 从 C# 调用 JS 方法?

jquery - 在固定的 div 内无限滚动内容循环