match patterns, but don't know how to replace them

时间:2019-02-18 00:19:05

标签: javascript node.js regex

I have string as

test\<string1\>again\<string2\>blabla

I set the regex pattern as below and tested with https://regex101.com/r/ZkIZvg/1

const regex = /\\<[^<]*\\\>/g

But how can I remove multiple \< and \> and get this string

test<string1>again<string2>blabla

So string1 and string2 need be kept as same.

I can't simply replace \< and \>, because I will only replace them, when they are paired, and I don't know how many pairs will be in string, maybe 1, 2, 3 or more pairs.

2 个答案:

答案 0 :(得分:2)

Capture the text between the <s, and replace with that captured group:

const input = String.raw`test\<string1\>again\<string2\>blabla`;
console.log(
  input.replace(/\\(<[^<]*)\\\>/g, '$1>')
);

答案 1 :(得分:-1)

// Relace backSlash with the empty string
const str = "test\<string1\>again\<string2\>blabla";
console.log(str.replace(/\\/g, ''));