tfsn20 发表于 2023-2-6 21:03:55

小小的正则问题

!(data/attachment/forum/202302/06/210331nkk9hg6l6wxh20dn.png)

cxxjackie 发表于 2023-2-6 21:03:56

const fn = (str, ...args) => {
    const raw = [...str.raw];
    const arr = ;
    while (raw.length) {
      arr.push(args.shift(), raw.shift());
    }
    return arr.map(s => s.replace(/\n/g, '')).join('');
};
const a = 'hello';
const b = 'world';
console.log(fn`2\n${a}
${b}`);

李恒道 发表于 2023-2-6 21:54:15

a.replace(/[\r\n]/g,'a')这样呢

李恒道 发表于 2023-2-6 21:54:26

https://stackoverflow.com/questions/9849754/how-can-i-replace-newlines-line-breaks-with-spaces-in-javascript

王一之 发表于 2023-2-6 22:15:26

"123 ".trim() 这呢?

tfsn20 发表于 2023-2-6 22:35:24

李恒道 发表于 2023-2-6 21:54
a.replace(/[\r\n]/g,'a')这样呢

只能先对文本处理了,事实上看不见的换行和文本里的\n字样是一样的,都是\n;
可以这样处理
```
String.raw`2\n
`.replace(/\n/mg, '').replace(/\\n/,'\n')
```
先用String.raw禁止转义,用来区分\n和看不见的换行,再把看不见的换行替换掉,最后将禁止转义再替换回去。不过有个 缺点,不能用变量,也就是要处理的文本只能直接放入String.raw里使用。
!(data/attachment/forum/202302/06/223454cdaxjwy88nzx9jta.png)
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/raw

tfsn20 发表于 2023-2-6 22:37:40

王一之 发表于 2023-2-6 22:15
"123 ".trim() 这呢?

也不行,\n会被识别为换行符,只能先禁止转义

tfsn20 发表于 2023-2-6 22:44:10

不过也是,用变量就转义了,要在没有转义前先禁止转义

tfsn20 发表于 2023-10-20 15:10:43

cxxjackie 发表于 2023-2-6 21:03


大佬,我有个需求,根据你的代码改了好多会也不行,是不是直接传递模板字符串变量的时候看的间的\n和看不见的\n没区别啊,这种情况下有解决办法吗
```
var templateStr = `1 2\n3 4 5
67`
function getTemplateStrNewlineCharacterNumber(str) {
    //some code
    return result
}
console.log(getTemplateStrNewlineCharacterNumber(templateStr))
```
匹配模板字符串不是\n的实际换行符,而不将\n视为换行符。

cxxjackie 发表于 2023-10-20 22:41:29

tfsn20 发表于 2023-10-20 15:10
大佬,我有个需求,根据你的代码改了好多会也不行,是不是直接传递模板字符串变量的时候看的间的\n和 ...

传变量不行,传出去就被转义成普通字符串了,标签函数是紧跟在模板字符串后面,在其初始化时作为一个预处理函数被使用的,而模板字符串在定义完成后就变成了一个普通字符串。
页: [1] 2
查看完整版本: 小小的正则问题