我处于客户端上下文中。 我有这个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/