2

I used other questions but so far only stumped.

This doesn't remove underscore.

Where is the mistake

var myString = str.toLowerCase().replace(/\W+/
 myString= myString.replace('/\_/g','');
2
  • 1
    Your first line seems to have gotten cut off. Commented Feb 4, 2017 at 16:38
  • It probably does not remove the underscore because the second line never executes, because the first line will result in a syntax error. Take a look at the console. Commented Feb 4, 2017 at 17:12

1 Answer 1

7

In general, you can remove all underscores from a string using

const myString = '_123__abc___-Some-Text_';
console.log(myString.replace(/_/g, ''));
console.log(myString.replaceAll('_', ''));

However, in this question, it makes sense to combine /_/g and /\W+/g regexps into one /[\W_]+/g. The \W pattern matches any char other than ASCII letters, digits and _, thus we need a custom character class to match both patterns.

Use

var myString = str.toLowerCase().replace(/[\W_]+/g,'');

where [\W_]+ matches one or more chars other than word chars and a _.

See the online regex demo.

Sign up to request clarification or add additional context in comments.

2 Comments

It matches other non letter symbols also
@AlexeyBaguk Whatever you mean by "non letter symbols" is unclear. The current OP problem is removing all occurrences of substrings that match \W and _ patterns, hence for the current question, .replace(/[\W_]+/g, '') is the appropriate answer. If you need a regex for special chars, see Check for special characters in string. If you need anything else, please provide more concrete details (a test case, fiddle, codepen, etc.) and state what behavior you seek.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.