简体   繁体   English

我想换。 和<br>使用javascript标记

[英]I want to replace . with <br>tag using javascript

I've tried this我试过这个

<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" onclick="strReplace();">Replace</button>

<script>
 function strReplace(){
        var myStr = document.getElementById("text");
        var mySte = myStr.textContent;
        console.log(mySte);
</script>

</body>

and I want this following outcome我想要以下结果

just some random text只是一些随机文本
random text随机文本

You can use this regex to find and replace string without breaking html: /(?!<[^>]+)\\.(?![^<]+>)/g您可以使用此正则表达式在不破坏 html 的情况下查找和替换字符串: /(?!<[^>]+)\\.(?![^<]+>)/g

 [myattr] { background-color: pink; } [myattr]:after { content: "this element's attribute is: " attr(myattr); background-color: lightgreen; margin: 1em; } p > span { background-color: lightblue; }
 <html> <head> <title>None</title> </head> <body> <p id="text">just some. random text. <span myattr="text.with.dots">nested.html</span> end. <span>i < 40. But i is also > 30. What are valid values of i?</span> </p> <button type="button" onclick="strReplace();">Replace</button> <script> function strReplace(){ var myStr = document.getElementById("text"); myStr.innerHTML = myStr.innerHTML.replace(/(?!<[^>]+)\\.(?![^<]+>)/g, "<br>"); console.log(myStr.innerHTML); } </script> </body>

To directly answer the question:直接回答问题:

var outputHtml = inputText.replace(/\./g, '<br />');

The Javascript replace method will by default replace the first instance of something (the first . in this case), so the g regex modifier tells it to replace them all.默认情况下, Javascript 替换方法将替换某些内容的第一个实例(在本例中为第一个 .),因此g正则表达式修饰符告诉它替换所有内容。 The \\. \\. in the regex is because .在正则表达式中是因为. is a special character in regexes.是正则表达式中的特殊字符。 This will replace every dot in the text.这将替换文本中的每个点。

What about ellipsis?省略号呢?

This technique won't work well on text that contains literal ellipsis, like this:这种技术不适用于包含文字省略号的文本,如下所示:

Hello world...

If your text is likely to contain this, and you want that to be ignored , then the following regex is more appropriate:如果您的文本可能包含此内容,并且您希望忽略该内容,则以下正则表达式更合适:

/[^\.](\.)[^\.]/g

This'll match any .这将匹配任何. which is not surrounded by other .没有被其他.

var outputHtml = inputText.replace(/[^\.](\.)[^\.]/g, '<br />');

Handling HTML处理 HTML

In the question here, the input is actually coming from the DOM.在这里的问题中,输入实际上来自 DOM。 We can't replace .我们无法替代。 on its innerHTML as it would replace content inside HTML tags as well.在其innerHTML 上,因为它也会替换HTML 标签内的内容。 So, if your input text is coming from the DOM like this (and not, say, a textarea), then the safest route is to apply the replacement only to text nodes .因此,如果您的输入文本来自这样的 DOM(而不是文本区域),那么最安全的方法是仅将替换应用于文本节点 That is done like this:这是这样做的:

 document.getElementById("start").addEventListener("click", () => { var inputNode = document.getElementById("text"); replace(inputNode); }); function replace(node) { if(!node) { return; } if (node.nodeName == '#text') { // We've found a text node. Apply the regex to it now. // Note that you can use either of the above regexes here. var inputText = node.textContent; var lines = inputText.split(/\\./g); if(lines.length > 1) { // It had at least one dot in it. // Swap in this new set, each with a <br /> between them. var parent = node.parentNode; var nextSibling = node.nextSibling; parent.removeChild(node); lines.forEach((line, i) => { if(i != 0){ // insert the <br> var br = document.createElement('br'); parent.insertBefore(br, nextSibling); } var textNode = document.createTextNode(line); parent.insertBefore(textNode, nextSibling); }); } } else { // Loop through each child node. // We go backwards such that completed replacements don't affect the loop. for(var i=node.childNodes.length - 1; i>=0; i--) { replace(node.childNodes[i]); } } }
 <html> <head> <title>None</title> </head> <body> <p id="text">just some random text. random text</p> <button type="button" id="start">Replace</button> </body> </html>

If you're starting from a HTML string inside a browser, you can then use the above replace method and the browsers internal parsing to safely only affect the actual text:如果您从浏览器中的 HTML 字符串开始,则可以使用上述替换方法和浏览器内部解析来安全地仅影响实际文本:

function replaceHtmlString(html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    replace(div);
    return div.innerHTML;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM