You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中检测文本回车键位置并替换为指定字符?

将文本中的换行符(\n)替换为字符"X"的JavaScript实现

要把文本里所有的换行符(\n)替换成字符"X",可以直接使用JavaScript的String.prototype.replace()方法结合全局正则表达式实现:

基础实现(仅处理\n)

const originalText = "Hey man, how are you?\nHere there is one enter above. And pressing 2 enters below.\n\nOk?";
const replacedText = originalText.replace(/\n/g, "X");
console.log(replacedText);
// 输出结果:"Hey man, how are you?XHere there is one enter above. And pressing 2 enters below.XXOk?"

代码说明

  • /\n/g 是全局匹配正则:\n 匹配换行符,g 修饰符确保替换所有符合条件的换行符(而非仅第一个)。

兼容Windows风格换行符(\r\n)

如果文本可能包含Windows系统的换行符(\r\n),可以调整正则表达式同时匹配两种换行格式:

const originalText = "Hi there\r\nThis has CRLF newline.\nThis has LF newline.\n\nEnd.";
const replacedText = originalText.replace(/\r?\n/g, "X");
console.log(replacedText);
// 输出结果:"Hi thereXThis has CRLF newline.XThis has LF newline.XXEnd."

代码说明

  • /\r?\n/g 中的?表示\r是可选的,这样不管是\r\n还是\n都会被替换成"X"。

内容的提问来源于stack exchange,提问作者Anthon Santhez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 22:12:40