使用 JavaScript RegExp 查找换页符。

front end technologyjavascriptweb development

换页符是分页符 ASCII 控制字符。它通常用于页面分隔符。当您想要插入分页符时,文本编辑器可以使用此换页符。它定义为 \f,其 ASCII 代码值为 120x0c

RegExp 是一个对象,它指定用于对字符串执行搜索和替换操作或用于输入验证的模式。 RegExp 是在 ES1 中引入的,并且所有浏览器都完全支持它。

现在,我们将检查如何使用 RegExp 在给定的文本中查找换页符 (\f)

语法

以下是换页符的语法 −

new RegExp("\f") 或简称为 /\f/

/\f/ 是在 ES1 中引入的。所有浏览器都完全支持它。例如 Chrome、IE、Safari、Opera、Firefox 和 Edge。

算法

  • 步骤 1 - 定义一个至少包含一个换页符的字符串。
  • 步骤 2 - 定义换页符的 RegExp 模式。
  • 步骤 3 - 对上面定义的字符串应用搜索(模式)以查找换页符的索引。
  • 步骤 4 - 显示结果,即换页符的索引。

注意,使用上述方法,我们将在给定的字符串中找到换页符的索引。

示例 1

在下面的程序中,我们使用字符串搜索(模式)在输入中查找换页符 (\f)字符串。我们使用 RegExp 作为 /\f/。字符串 search() 方法返回匹配字符的索引。因此它返回换页符的索引。

<html> <body> <p>Finding the position of a form feed character</p> <p>The position is : <span id="result"></span> </p> <script> let text = "Hello, Devika. \fWelcome back"; let pattern = /\f/; let result = text.search(pattern); document.getElementById("result").innerHTML = result; </script> </body> </html>

如果找到换页符,它将返回位置,否则它将返回 -1。

示例 2

在下面的程序中,我们取一个没有换页符的字符串,并尝试在字符串中找到换页符。看看我们的输出是什么样的。

<!DOCTYPE html> <html> <body> <h2>RegExp \f finding</h2> <p id = "result"></p> <script> const text = "Hello, Devika. Welcome back"; const regExp = /\f/; const output = text.search(regExp); if(output == -1) { document.getElementById("result").innerHTML = "No form feed character present. "; } else { document.getElementById("result").innerHTML = "Index of form feed character: " + output; } </script> </body> </html>

示例 3

查找和替换换页符

我们还可以替换给定文本中的换页符。在下面的程序中,我们查找换页符并使用 String split() 方法将其替换为空格。

<!DOCTYPE html> <html> <body> <h1>Replace form feed line character</h1> <p>After replacing the form feed character: <span id= "result"></span> </p> <script> var text = "Hello,\fDevika.\fWelcome back."; var result = text.split("\f").join(" "); document.getElementById("result").innerHTML = result; </script> </body> </html>

示例 4

在下面的程序中,我们找到换页符,并使用 String replace() 方法将其替换为空格。

<!DOCTYPE html> <html> <body> <h1>Replace form feed line character</h1> <p>After replacing the form feed character : <span id= "result"></span> </p> <script> var text = "Hello,\fDevika.\fWelcome back."; var result = text.replace(/\f/g, " "); document.getElementById("result").innerHTML = result; </script> </body> </html>

此处,"g"用于执行全局匹配,即它不会在第一次出现时停止,而是会查找所有出现的情况。我们还可以用其他方式替换换页符。这里,我仅解释了几种更简单的方法。

RegExp 具有修饰符,如 g、i、m。"g"用于执行全局匹配,"i"用于执行不区分大小写的匹配,"m"用于执行多行匹配。

我们已经了解了如何使用 JavaScript 中的 RegExp 在给定文本中查找换页符。希望这能让您明白。


相关文章