1

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','');
HomeMade
  • 552
  • 4
  • 10
  • 21
  • 1
    Your first line seems to have gotten cut off. – Barmar Feb 04 '17 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. –  Feb 04 '17 at 17:12

1 Answers1

6

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    It matches other non letter symbols also – Alexey Baguk Aug 04 '21 at 07:42
  • 1
    @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](https://stackoverflow.com/a/32311188/3832970). If you need anything else, please provide more concrete details (a test case, fiddle, codepen, etc.) and state what behavior you seek. – Wiktor Stribiżew Aug 04 '21 at 12:50