我正在寻找一种智能方法来在长字符串中的特殊字符后添加空格。
let str = "this\is\an\example\for\a\long\string";
str = str.split("\\").join("\\ ");
这会产生:
"this\ is\ an\ example\ for\ a\ long\ string";
我正在寻找更通用的东西来一次捕获多个特殊字符,如下所示:
let str = "this.is.a\long-mixed.string\with\many.special/characters";
str = str.split(/[.\-_]/).join(/[. \- _ ]/); //note the white spaces after the dot, hyphen and slash. I need to cover as much special chars as possible.
编辑
我需要这个来支持多语言。所以基本上英语\阿拉伯语\希伯来语单词不应该有空格,而只能在特殊字符后插入空格。
最佳答案
你可以这样做
因此,通过替换,我可以匹配除字母和数字之外的任何内容。而不是简单地添加一个空格。
let str = "this.is.a\long-mixed.string\with\many.special/characters";
str = str.replace(/([\W_])/g, "$1 ");
console.log(str);
([\W_])
- 匹配除字母和数字之外的任何内容。
关于javascript - JS\TS - 无法在基于多个特殊字符的字符串中添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804123/