首页 > 解决方案 > Javascript 使用 RegEXP 删除(但不包括)特殊字符之间的字符

问题描述

我有一个字符串如下:

var s = "1111 type reallycoolsentence\text.json\n1111 type anotherreallycoolsentence text2.json

我试图摆脱反斜杠之间的字符。

想要的结果:

s = "type reallycoolsentence\\type anotherreallycoolsentence"

我知道如何在不删除特殊字符的情况下删除两个特殊字符之间的字符以外的所有内容。堆栈上的每个答案也包括删除它们:(

标签: javascriptregexstringparsing

解决方案


将反斜杠放在替换字符串中。

请注意,您需要将它们加倍以获得文字反斜杠,因为反斜杠是字符串文字中的转义前缀。

var s = "1111 type reallycoolsentence\\text.json\\n1111 type anotherreallycoolsentence text2.json";
var result = s.replace(/\\.*\\/, '\\\\');
console.log(result);

此结果与您的示例中的结果不匹配,但那是因为它与您对您想要做什么的描述不匹配。我实现了描述。


推荐阅读