0

i have an array of strings with that contain a number of different characters. i am looping through the array and using the .replace(RegExp,Replacement) method, But i cant seem to get it to work properly.The expression that i am using is "/[^\w\d]". I am trying to remove anything that is not a letter or number including Spaces and replace it with an "_"(to make it nice for a file name). Ive tested the regex above and it is supposed to be correct. But i am getting weird and unwanted results.The following code will reproduce my problem.

var StringArray = ["ABCdef123®","ABCdef/123®","ABCde f123®","ABCde/f123®","AB Cde\\f123®"];
const myRegex = new RegExp("/[^\w\d]");
var NewString;
var counter = 0;

StringArray.forEach(function(item){
 NewString = item.replace(myRegex,"_");
 console.log("Old String: " + item);
 console.log("New String: "+ NewString);
 counter++;
})

The Output will look like this

Old String: ABCdef123®
New String: ABCdef123®

Old String: ABCdef/123®
New String: ABCdef_23®

Old String: ABCde f123®
New String: ABCde f123®

Old String: AB Cde/f123®
New String: AB Cde_123®

Old String: AB Cde\f123®
New String: AB Cde\f123®

it will not find backslashes or the "®" symbol. and when it does find something it is also removing the following character. what am i doing wrong here?

B00100100
  • 33
  • 5
  • 3
    You want just `const myRegex = /[^\w\d]/;` – Pointy Aug 15 '18 at 20:33
  • This actually solved my issue, But i also needed to add the global match (/[^\w\d]/g) at the end for it to work properly.i haven't tried the other answers yet but each has its own variation is any one better than the other? – B00100100 Aug 15 '18 at 20:44
  • The btmorex answer is correct then: `/\W/g` – Pointy Aug 15 '18 at 20:45

3 Answers3

1

You need to use /\W/ which means: not a letter, digit or _:

var StringArray = ["ABCdef123®","ABCdef/123®","ABCde f123®","ABCde/f123®","AB Cde\\f123®"];
const myRegex = new RegExp(/\W/, 'g');
var NewString;
var counter = 0;

StringArray.forEach(function(item){
 NewString = item.replace(myRegex,"_");
 console.log("Old String: " + item);
 console.log("New String: "+ NewString);
 counter++;
})
Kosh
  • 16,966
  • 2
  • 19
  • 34
1
const myRegex = /\W/g;

works. You want the g to replace all occurrences. Your new Regexp syntax is wrong. It shouldn't include the slash.

btmorex
  • 476
  • 5
  • 16
1

There's actually a regex for non-letter-and-non-digits, it's \W.

const myRegex = /\W/g;

It's supposed to do the trick :)

Ben Sh
  • 49
  • 6