-1

How can i convert a string with regex, so that it contains just alphabetical (a-z) or a hyphen. It should get rid " ' ! ? . and so on. Even if they appear multiple times.

// if i have e.g.
var test = '"test!!!"';

// how can i get the value "test"?

Can sombody help. RegEx is totaly new to me.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
joh
  • 3
  • 2

5 Answers5

1

Simply replace the characters you don't want:

'"test!!!"'.replace(/[^a-z-]/gi, '')

[^a-z-] matches all characters but a-z and the hyphen. The /g flag makes the regexp apply multiple times. The /i flag (optional) makes it match case-insensitively, i.e. not replace upper-case characters.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • @Bergi Are you sure? What JavaScript engine are you using? Make sure that you don't forget the `/g` flag. – phihag Oct 14 '12 at 21:38
  • Yes, but you forgot it at first… – Bergi Oct 14 '12 at 21:39
  • whould this also replace a hyphen which appears between a-z caracters, like "word-word"? – joh Oct 15 '12 at 09:08
  • @user1745578 Yes. The expression matches characters, and does not care about order. – phihag Oct 15 '12 at 09:15
  • so how whould it be if it whould care about order? like matching the hyphen after an end and ignoring it when it appears inbetween? – joh Oct 15 '12 at 09:39
  • Then you'd use [lookaround assertions](http://www.regular-expressions.info/lookaround.html). However, [lookbehind assertions are not supported in JavaScript](http://stackoverflow.com/questions/9779578/javascript-negative-lookbehind). Therefore, you'd have to join the matches of allowed words instead of filtering out the invalid characters. – phihag Oct 15 '12 at 09:44
1

That's quite simple: You build a character class that matches everything except those chars you want and remove them by replacing each occurence (global flag) with the empty string:

return str.replace(/[^a-z-]/g, "");
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0
 str = "hello!! my + name $ is slim-shady";
   console.log(str.replace(/[^a-z-]+/g, ''));

$ node src/java/regex/alphanum.js 
hellomynameisslim-shady
0

Use the replace method for any string variable and specify the characters you wish to remove.

Here's an example:

 var sampleString = ("Hello World!!");    //Sample of what you have. 
 var holdData = sampleString.replace(/!!/gi, '');
 window.alert(holdData);
Dayan
  • 7,634
  • 11
  • 49
  • 76
-1
var str = "test!!!";
str = str.replace(/[^A-Za-z\-]/g,"");
Kaustubh Karkare
  • 1,083
  • 9
  • 25