Search code examples
javascriptregexunicodereplacexregexp

JS XRegExp Replace all non characters


My objective is to replace all characters which are not dash (-) or not number or not letters in any language in a string.All of the #!()[], and all other signs to be replaced with empty string. All occurences of - should not be replaced also. I have used for this the XRegExp plugin but it seems I cannot find the magic solution :) I have tryed like this :

var txt = "Ad СТИНГ (ALI) - Englishmen In New York";
var regex = new XRegExp('\\p{^N}\\p{^L}',"g");
var b = XRegExp.replace(txt, regex, "")

but the result is : AСТИН(AL EnglishmeINeYork ... which is kind of weird

If I try to add also the condition for not removing the '-' character leads to make the RegEx invalid.


Solution

  • \\p{^N}\\p{^L} means a non-number followed by a non-letter.

    Try [^\\p{N}\\p{L}-] that means a non-number, non-letter, non-dash.

    A jsfiddle where to do some tests... The third XRegExp is the one you asked.