Home >Web Front-end >Front-end Q&A >How to use regular expression to replace newline characters in javascript

How to use regular expression to replace newline characters in javascript

青灯夜游
青灯夜游Original
2022-03-28 16:04:418550browse

Regular method of replacing newline characters: 1. Use the replace() function, the syntax is "String object.replace(/[\r\n]/g,'replacement value')"; 2. Use replaceAll () function, syntax "string object.replaceAll(/[\r\n]/g,'replacement value')".

How to use regular expression to replace newline characters in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript regular replacement of newlines

Method 1: Use the replace() function

replace The () method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.

Example:

let a = '\n换行个阿斯蒂芬\r换行个阿斯蒂芬ABCD';
console.log(a);
let b = a.replace(/[\r\n]/g,'');
console.log(b);

How to use regular expression to replace newline characters in javascript

Method 2: Use replaceAll() function

replaceAll() method is used Replace some characters with other characters in a string, or replace a substring that matches a regular expression. This function will replace all matching substrings.

let a = '换行个阿斯蒂芬\r\n换行个阿斯蒂芬\nABCD';
console.log(a);
let b = a.replaceAll(/[\r\n]/g,'!');
console.log(b);

How to use regular expression to replace newline characters in javascript

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to use regular expression to replace newline characters in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn