nodumbqs
nodumbqs

Reputation: 101

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

Upvotes: 2

Views: 67

Answers (2)

Jack Fleeting
Jack Fleeting

Reputation: 24930

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

Upvotes: 1

Barmar
Barmar

Reputation: 782344

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.

Upvotes: 2

Related Questions