Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular Expression in JavaScript with multiple conditions

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use this regex in unicode for search:

[^\p{Letter}\p{Number}#]+

and replace with empty string.

RegEx Demo

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}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading