I would like to remove in javascript from my text_string all characters that are not letters (in all languages) and numbers. I can do it individually. But how can I put both in ONE expression, so that both conditions are true at the same time?
var text_string = '!#Ab+Z1_↕.🍏2ü翻訳';
text_string = text_string.replace(/\P{Letter}/gu, '');
text_string = text_string.replace(/\P{Number}/gu, '');
text_string = text_string.replace(/[^#]/, '');
// should be replaced to #AbZ12ü翻訳
>Solution :
You can use this regex in unicode for search:
[^\p{Letter}\p{Number}#]+
and replace with empty string.
Code:
const regex = /[^\p{Letter}\p{Number}#]+/gu;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('[^\\p{Letter}\\p{Number}#]+', 'gu')
const str = `!#Ab+Z1_↕.🍏2ü翻訳`;
const result = str.replace(regex, '');
console.log(result);
RegEx Breakup:
[^\p{Letter}\p{Number}#]+: In a character class match any character that is not#not a unicode letter and not a unicode number.
Remember that \p{something} is inverse of \P{something}