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

使用localeCompare对比文本时忽略换行的实现方案求助

忽略换行符的文本对比实现方案

我正在开发一款Photoshop插件,用于遍历每个textLayer中的文本,并将其与包含相同文本的电子表格数据匹配,实现多语言翻译功能(表格含多语言数据)。

目前我需要对比textLayer中的英文文本与表格英文行,判断是否存在对应翻译,使用localeCompare进行匹配的代码如下:

if (textLayer.localeCompare(translationText, 'en', { sensitivity: 'base' }) === 0) {
    console.log(textLayer + translationText[l][0] + ' %c !Matches! ', 'background: #222; color: #bada55');
}

普通文本可正常匹配,控制台输出:

The Gift EditThe Gift Edit  !Matches!
We got just the right styles for you.We got just the right styles for you.  !Matches!

但发现当其中一方文本包含换行符时会导致匹配失败,请问如何实现忽略换行符的文本对比?


解决方案

你可以在对比前先对两个文本进行预处理,移除所有换行符(包括\n、\r以及\r\n),再用localeCompare进行匹配。

修改后的代码示例:

// 定义移除换行符的工具函数
const removeLineBreaks = (str) => {
    return str.replace(/[\n\r]/g, '');
};

// 预处理两个文本
const cleanedTextLayer = removeLineBreaks(textLayer);
const cleanedTranslationText = removeLineBreaks(translationText);

// 执行匹配
if (cleanedTextLayer.localeCompare(cleanedTranslationText, 'en', { sensitivity: 'base' }) === 0) {
    console.log(cleanedTextLayer + cleanedTranslationText + ' %c !Matches! ', 'background: #222; color: #bada55');
}

补充说明

  • 正则表达式/[\n\r]/g会全局匹配并移除所有换行相关的字符,覆盖Windows(\r\n)、Unix/Linux(\n)和旧Mac(\r)的换行格式。
  • 如果还需要忽略多余空格(比如换行后可能伴随的空格),可以在预处理时进一步处理,比如用str.replace(/[\n\r\s]+/g, ' ').trim()来合并连续空白字符并去除首尾空格,根据实际需求调整即可。

内容的提问来源于stack exchange,提问作者Mikkel Fennefoss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:17:06