在本教程中,我们将学习如何使用 
 标记替换 javascript 代码中的所有换行符。有多种方法可以使用 
 标记替换所有换行符。下面给出了一些方法 -
使用 string replace() 方法和 regex在此方法中,我们使用 string.replace() 方法将纯文本中的所有换行符替换为 
 标记。这里的regex指的是我们在 string.replace() 方法中编写的正则表达式。
语法以下是使用replace( )方法 -
sentence.replace(/(?:\r|\r|)/g, "<br>");
这里句子是带换行符的字符串,replace()方法的第一个参数是正则表达式。
算法第 1 步 - 定义一个带换行符的字符串并显示它。
第 2 步 - 对上面定义的字符串应用 replace() 方法。使用上述语法来应用替换方法。
步骤3 - 显示步骤2中获得的字符串。所有换行符都替换为.
示例我们可以使用下面给出的代码,使用正则表达式将所有换行符替换为 
 标记。<!doctype html><html><body>   <p id="br"></p>   <button onclick="linebreak()">replace</button>   <script>      let sentence = `javascript is a dynamic computer      programming language for web.      javascript can update and change both html and css`;      let br = document.getelementbyid("br");      br.innerhtml = sentence;      function linebreak() {         // replace the line break with <br>         sentence = sentence.replace(/(?:\r|\r|)/g, "<br>");         // update the value of paragraph         br.innerhtml = sentence;      }   </script></body></html>
在上面的代码中, string.replace() 方法检查所有 3 种换行符,即 \r
、
 和 \r,并使用\g 标签,然后用 
 标签替换它们。
使用 split() 和 join() 方法在此方法中,使用分隔符和返回一个子字符串数组,然后将这些子字符串组合起来形成一个数组并传递 
 ,以便每个连接都包含 
。
语法以下是语法应用 split() 和 join() 方法 -
sentence.split("").join("<br />");
这里句子是带有换行符(
)的字符串,我们要用
替换它。
算法第 1 步 - 定义带换行符的字符串并显示它。
步骤 2 - 对上面定义的字符串应用 split() 和 join() 方法。使用上述语法来应用替换方法。
步骤3 - 显示步骤2中获得的字符串。所有换行符都替换为.
示例我们可以使用下面给出的代码,使用 split 和 join 方法将所有换行符替换为 
 标记<!doctype html><html><body>   <p id="br"></p>   <button onclick="linebreak()">change</button>   <script>      let sentence = `javascript is a dynamic computer      programming language for web.      javascript can update and change both html and css`;      let br = document.getelementbyid("br");      br.innerhtml = sentence;      function linebreak() {         // replace the line break with <br>         sentence = sentence.split("").join("<br />");         // update the value of paragraph         br.innerhtml = sentence;      }   </script></body></html>
在上面的代码中,使用内置方法将行字符串替换为 br 标记字符串。使用 split() 方法使用分隔符分割字符串,然后使用 join() 方法连接分割后的子数组,形成一个数组。
以上就是如何使用 javascript 替换换行符?的详细内容。
   
 
   