-1

I'm trying to match symbol sequence according to these rules:

  1. it's located at the start of the string
  2. case insensitive
  3. it begins with letter V or N
  4. optional space follows
  5. - or characters follows (only one of them)
  6. optional space follows

Here are example strings that it should match and expression I tried to make using google results :) :

var str = "V - ";
/*var str = "N - ";
var str = "V- ";
var str = "N -";
var str = "N –";
var str = "V– ";*/
str.replace(/^(V|N)\s(-|–)\s/i, 'replaced'); 
alert(str);

However it doesn't seem to work. Can someone help me please and explain how it is used, what I did wrong? Thanks

simPod
  • 11,498
  • 17
  • 86
  • 139

3 Answers3

2

try this

(V|H|v|h)\s*(-|–)\s*

the \s* gives you the options whitespace

also if you want to find multiple use /g

blackmind
  • 1,286
  • 14
  • 27
1

you are so close. the str.replace function doesn't actually modify str, but it returns a modified copy of it, so what you want is

var str = "V - ";
/*var str = "N - ";
var str = "V- ";
var str = "N -";
var str = "N –";
var str = "V– ";*/
var str2 = str.replace(/^(V|N)\s?(-|–)\s/i, 'replaced'); 
alert(str2);

also, notice the '?' that I added to your expression, that makes the space optional (use * instead for 0 or more spaces)

hair raisin
  • 2,618
  • 15
  • 13
1

The regex can be simplified:

alert(str.replace(/^[VN]\s*[-–]\s*/i, 'replaced'));

You had expressions like (V|N), but the alternation group is unnecessary when it's single characters. It's equivalent to [VN], which indicates all the possible matches for a single character.

Brian Stephens
  • 5,161
  • 19
  • 25