2

Following regex replaces " >" or " > " or "> " character with "/".

tempKeyword = tempKeyword.replace(/( > )|( >)|(> )/g,'/');

How can I make this better?

Thanks!

IfOnly
  • 540
  • 1
  • 4
  • 17

2 Answers2

4

Have a try with this one:

tempKeyword = tempKeyword.replace(/\s*>\s*/g,'/');

Edit 2 according to comment below:

tempKeyword = tempKeyword.replace(/(?:^|\S+\s)>(?:\s\S+|$)/g,'/');
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    This one is good. However, if @Bramha needs 0 or 1 space at the beginning and 0 or 1 space after > then it should be \s{0,1}>\s{0,1}. – Tobiasz Feb 18 '14 at 10:19
  • 1
    It should be mentioned that space and *any white-space character* are different things. Also, as this RegEx matches a wider variety of cases and variable lengths, I'm assuming that OPs version is still more "optimized" than this. – MildlySerious Feb 18 '14 at 10:20
  • the star would match 0 or more, as the I read the OP's question he wants 0 or 1 spaces? – woutervs Feb 18 '14 at 10:21
  • I am using this match regex keyword.match(/\s{0,1}>\s{0,1}/g) But I don't want to match in case the '>' character is present at start or end> How can I modify this regex to achieve this e.g. motor> --- should fail >motor --- should fail motor > --- should pass > motor --- should pass motor > car ---- should pass motor >car ---- should fail motor> car ---- should fail – IfOnly Feb 18 '14 at 12:15
  • @M42: This is not working in case of 'motor >' and '> motor'. This should pass. It should fail if there is no space 'motor>' and '>motor' – IfOnly Feb 18 '14 at 12:25
  • @M42: I also want to be as good as u in regex. How can I achieve that? and if there are any ddocuments or sites that are helpful please share. Thanks in advance. – IfOnly Feb 19 '14 at 04:47
  • @Bramha: here are usefull sites: http://www.rexegg.com/ and http://www.regular-expressions.info/ – Toto Feb 19 '14 at 08:10
2

You can make your regular expression like so:

/ ?> ?/g

What we do here is saying if you find > with 0 or 1 space before then match. (the ? operator stands for 0 or 1)

woutervs
  • 1,500
  • 12
  • 28
  • 1
    It is probably better to use \s as a white space because of Unicode white space characters (ref.http://stackoverflow.com/questions/2429146/javascript-regular-expression-single-space-character) – Tobiasz Feb 18 '14 at 10:24
  • I agree, however the OP asked for an optimization, the \s is less optimized (same with the \d and \w) as it needs to test for more possible hits. Therefore I've chosen to just take the space. But indeed if he were testing on unicode documents he should use the \s instead. – woutervs Feb 18 '14 at 10:26