0

I'm trying to strip a string of all characters that are not a letter or a number. I tried String.prototype.replace with a regular expression, but it didn't remove the expected characters:

this.colorPreset1 = this.colorPreset1.replace(/^[0-9a-zA-Z]+$/, '');
tony19
  • 125,647
  • 18
  • 229
  • 307
codernoob8
  • 434
  • 1
  • 9
  • 24

3 Answers3

2
this.colorPreset1=this.colorPreset1.replace(/[^0-9a-zA-Z]/g, '');

The character group was changed to a exclusion group. [^] will match any character not in the list. As you had it, it would only match the characters you wanted to keep.

The anchors for the string were removed - You're wanting to replace any non-alpha numeric characters, so it doesn't matter where they're located.

The global flag //g was added so it will replace all matches instead of just the first one.

Trenton Trama
  • 4,890
  • 1
  • 22
  • 27
  • It's beneficial to explain why the code you posted works. It encourages understanding rather than just copy/pasting code. – Strikegently Oct 08 '18 at 17:02
2

By adding ^ and $ around your regular expression, you explicitly tell it to match strings starting and ending with this pattern.

So it will replace the searched pattern only if if all the content of the string matches the pattern.

If you want to match each occurence of non numerical or alphabetical characters, you will have to remove the ^ start constraint and the $ end constraint, but also will have to change the pattern itself:

[A-Za-z0-9]

matches alphabetical or numerical characters, you want the opposite of that (to inverse a character class add a ^ at the start of the character class:

[^A-Za-z0-9]

finally add the g option to the regex to tell it to match each occurence (otherwise only the first occurence will be replaced):

/[^A-Za-z0-9]+/g
remix23
  • 2,632
  • 2
  • 11
  • 21
0

JavaScript RegEx replace will only replace the first found value. If you specify the g argument in your pattern, it denotes Global or "replace all."

this.colorPreset1=this.colorPreset1.replace(/[^0-9a-zA-Z]/g, '');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

What does the regular expression /_/g mean?

Strikegently
  • 2,251
  • 20
  • 23