简体   繁体   English

Javascript 使用 RegEXP 去除(但不包括)特殊字符之间的字符

[英]Javascript use RegEXP to remove characters between (but not including) special characters

I have a string as follows:我有一个字符串如下:

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

I'm trying to get rid of the characters between the backslashes.我试图摆脱反斜杠之间的字符。

Wanted result:想要的结果:

s = "type reallycoolsentence\\type anotherreallycoolsentence"

I know how to remove everything except characters between two special characters WITHOUT removing the special characters.我知道如何在不删除特殊字符的情况下删除两个特殊字符之间的字符以外的所有内容。 Every answer on stack includes removing them too:(堆栈上的每个答案也包括删除它们:(

Put the backslashes in the replacement string.将反斜杠放在替换字符串中。

Note that you need to double them to get literal backslashes because backslash is an escape prefix in string literals.请注意,您需要将它们加倍以获得文字反斜杠,因为反斜杠是字符串文字中的转义前缀。

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

This result doesn't match the result in your example, but that's because it doesn't match your description of what you want to do.此结果与您的示例中的结果不匹配,但那是因为它与您对要执行的操作的描述不匹配。 I implemented the description.我实现了描述。

For those of us who don't like regex...:对于我们这些不喜欢正则表达式的人......:

  s = "1111 type reallycoolsentence text.json\n1111 type anotherreallycoolsentence text2.json"
  wArray = s.split(" ");  
  wArray = wArray.filter( value => value !== "1111");
  wArray = wArray.filter(value => !value.includes('.json'));
  result = wArray.join(" ");

Output: Output:

type reallycoolsentence type anotherreallycoolsentence

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM