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

Viewed 62

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 :(

2 Answers

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:

type reallycoolsentence type anotherreallycoolsentence
Related