4

I am trying to replace special characters except numbers with the space from a string which could be in English or Arabic language.

I have used the below regex which works perfectly for English language by replacing special characters with space from the string but, in Arabic language it replace the Arabic characters too.

data[i].replace(/[^\w\s]/gi, '');

Please help me to find the regex which will replace the special characters with space but not English and Arabic characters and numbers. Thank you.

adiga
  • 34,372
  • 9
  • 61
  • 83
Rohit Bhosale
  • 83
  • 1
  • 5
  • 1
    Possible duplicate of [Regular Expression Arabic characters and numbers only](https://stackoverflow.com/questions/29729391/regular-expression-arabic-characters-and-numbers-only) – adiga Feb 22 '19 at 12:52
  • Add a `\w` or `a-zA-Z` to the above duplicate's answer's character class – adiga Feb 22 '19 at 12:52
  • I want to replace the special characters with space. I don't want regex which accept english and arabic language with space. – Rohit Bhosale Feb 22 '19 at 12:57

1 Answers1

1

You can replace everything but the Arabic and alphanumeric characters like this:

(Arabic regex borrowed from here)

const str = "ء-يabc##123-2++"
const replaced = str.replace(/[^\w\u0621-\u064A\s]/gi, ' ');
console.log(replaced)
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 2
    Keep in mind that this not cover the full [Arabic Unicode range](https://unicode-table.com/en/blocks/arabic/). Which is from `0600` up to `06FF`. I don't know what the characters not included by the above mean, but you should at least take this into consideration. – 3limin4t0r Feb 22 '19 at 13:19
  • @JohanWentholt interesting. In the link I mentioned, most of the answers use this range. But, [some other answers](https://stackoverflow.com/a/40340310/3082296) do use the range you mentioned. – adiga Feb 22 '19 at 13:27
  • 1
    It comes down to each specific use case. If you want to whitelist all Arabic characters, or only Arabic letters and/or numbers (exclude things like `؆`). This is for the reader to decide and pick the ranges they seem fit. – 3limin4t0r Feb 22 '19 at 13:30