JavaScript RegExp f Metacharacter (original) (raw)

Last Updated : 10 Dec, 2024

The \f metacharacter in JavaScript regular expressions matches a form feed character. Form feed (\f) is a control character used to indicate a page break in text. While it is rare in modern applications, it can still appear in old documents or text files.

JavaScript `

let regex = /\f/; let str1 = "Hello\fWorld"; let str2 = "Hello World"; console.log(regex.test(str1)); console.log(regex.test(str2));

`

The pattern \f matches the form feed character (\f) in str1 but not in str2, as the latter lacks a form feed.

Syntax:

/\f/

Key Points

Real-World Examples

1. Detecting Form Feeds

JavaScript `

let regex = /\f/; let str = "This is a form feed\fexample."; if (regex.test(str)) { console.log("Form feed detected!"); } else { console.log("No form feed found."); }

`

Output

Form feed detected!

2. Removing Form Feeds

JavaScript `

let str = "Text with form feed\fcharacter."; let cleanedStr = str.replace(/\f/g, ""); console.log(cleanedStr);

`

Output

Text with form feedcharacter.

This example removes all occurrences of \f from the string.

3. Counting Form Feeds

JavaScript `

let str = "Line 1\fLine 2\fLine 3"; let regex = /\f/g; let count = (str.match(regex) || []).length; console.log(count);

`

Counts the number of form feed characters in the string.

4. Splitting Text by Form Feeds

JavaScript `

let str = "Page1\fPage2\fPage3"; let pages = str.split(/\f/); console.log(pages);

`

Output

[ 'Page1', 'Page2', 'Page3' ]

Splits a multi-page document into separate pages based on the form feed character.

5. Highlighting Form Feeds in Text

JavaScript `

let str = "First\fSecond\fThird"; let highlighted = str.replace(/\f/g, "[FORM FEED]"); console.log(highlighted);

`

Output

First[FORM FEED]Second[FORM FEED]Third

Replaces form feed characters with a visual marker for better clarity.

Common Patterns Using \f

/\f/

str.replace(/\f/g, "");

str.split(/\f/);

(str.match(/\f/g) || []).length;

str.replace(/\f/g, " ");

Limitations

Why Use the \f Metacharacter?

Conclusion

The \f metacharacter is a niche tool in regex, primarily useful for dealing with legacy text or specialized formatting requirements.