Regular Expression Slash Matching

I don't have much experience with JavaScript, but I'm trying to create a tag system that will use / instead of using @ or # .

 var start = /#/ig; // @ Match var word = /#(\w+)/ig; //@abc Match 

How to use / instead of # . I tried to make var slash = '/' and add + slash + , but that failed.

+73
javascript regex
May 20 '13 at 19:44
source share
5 answers

You can avoid this.

 /\//ig; // Matches / 

or just use indexOf

 if(str.indexOf("/") > -1) 
+96
May 20 '13 at 19:46
source share

You need to avoid / using \ .

 /\//ig // matches / 
+20
May 20 '13 at 19:46
source share

If you want to use / , you need to avoid it with \

 var word = /\/(\w+)/ig; 
+6
May 20 '13 at 19:46
source share

In regular expressions, β€œ/” is a special character that needs to be escaped (AKA is marked with a before it denies any specialized function that it can perform).

Here is what you need:

 var word = /\/(\w+)/ig; // /abc Match 

Read the RegEx special characters here: http://www.regular-expressions.info/characters.html

+6
May 20 '13 at 19:47
source share

I ran into two problems related to the above when extracting text with delimiters \ and / and found a solution that works for both except using new RegExp , which requires \\\\ at the beginning. This data is in Chrome and IE11.

Regular expression

 /\\(.*)\//g 

does not work. I think that // interpreted as the beginning of the comment, despite the escape character. Regular expression (equally true in my case, although not in general)

 /\b/\\(.*)\/\b/g 

doesn't work either. I think the second / terminates the regex despite the escape character.

What works for me is to represent / as \x2F , which is the hexadecimal representation of / . I find this more efficient and understandable than using new RegExp , but of course he needs a comment to identify the hex code.

0
Oct 31 '14 at 1:47
source share



All Articles