Skip to main content
Mohamed Hameed21513110
Inspiring
September 19, 2022
Answered

Delete more than one strange letter from the word

  • September 19, 2022
  • 1 reply
  • 282 views

I know this code
.replace(/-/g, '');
Delete only one letter of a word or text
But there are some words that contain more than one symbol or strange character such as ( ! @ # $ % ^ & * )

I just want to modify the code to delete any letter or group of letters inside the word

This topic has been closed for replies.
Correct answer Stephen Marsh

@Mohamed Hameed21513110 

 

That appears to be a literal hyphen character, not a "metacharacter".

 

To delete anything that is not an upper/lowercase alphabetical letter, number, hyphen, underscore or space:

 

.replace(/[^A-Za-z0-9-_ ]/g, '');

 

Basically, whatever literal character inside the [^] is retained. You are specifying what to keep, with everything not explicitly set removed.

 

The input string of:

 

MY TEXT! @ # $ % ^ & *

 

Would result in:

 

MY TEXT       

 

However, there would be some consecutive garbage word spaces left at the end, therefore, a second regex cleanup would be required:

 

.replace(/ +$/g, '');

 

That being said, regex is very much case-dependent, so generic replies as above may or may not be 100% successful without real examples.

1 reply

Stephen Marsh
Community Expert
Stephen MarshCommunity ExpertCorrect answer
Community Expert
September 19, 2022

@Mohamed Hameed21513110 

 

That appears to be a literal hyphen character, not a "metacharacter".

 

To delete anything that is not an upper/lowercase alphabetical letter, number, hyphen, underscore or space:

 

.replace(/[^A-Za-z0-9-_ ]/g, '');

 

Basically, whatever literal character inside the [^] is retained. You are specifying what to keep, with everything not explicitly set removed.

 

The input string of:

 

MY TEXT! @ # $ % ^ & *

 

Would result in:

 

MY TEXT       

 

However, there would be some consecutive garbage word spaces left at the end, therefore, a second regex cleanup would be required:

 

.replace(/ +$/g, '');

 

That being said, regex is very much case-dependent, so generic replies as above may or may not be 100% successful without real examples.

Mohamed Hameed21513110
Inspiring
September 20, 2022

@Stephen Marsh 

Thank you for your continued cooperation with me
You are doing a great favor with everyone
With all my heart I thank you very much and wish you success always