Regex to replace single backslashes, excluding those followed by certain chars

前端 未结 3 1364
闹比i
闹比i 2021-01-12 17:11

I have a regex expression which removes any backslashes from a string if not followed by one of these characters: \\ / or }.

It should turn this string:

<         


        
3条回答
  •  攒了一身酷
    2021-01-12 17:51

    The required regex is as simple as \\.

    You need to know however, that the second argument to replace() can be a function like so:

    result = string.replace(/\\./g, function (ab) { // ab is the matched portion of the input string
        var b = ab.charAt(1);
        switch (b) { // if char after backslash
        case '\\': case '}': case '/': // ..is one of these
            return ab; // keep original string
        default: // else
            return b; // replace by second char
        }
    });
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题