2

I am an amateur with regular expressions, but I have a need to extract a piece of string in javascript.

My current (working) code is:

var txt='Icon/something/0.gif'; var re1='.*?'; var re2='(?:[a-z][a-z]+)'; var re3='.*?'; var re4='((?:[a-z][a-z]+))'; var p = new RegExp(re1+re2+re3+re4,["i"]); var m = p.exec(txt); var word = m[1]; //something 

However I can't imagine that us the most efficient way of doing it.

What I need to do is extract "something" from a string like this:

Icon/something/0.gif 

or "somethingelse" from:

Icon/somethingelse/10.gif 

Is there a more compact regex I can use?

3
  • 3
    Sounds like Code Review Commented Jul 15, 2014 at 17:24
  • 2
    RegExp flags are strings, not arrays, and unless you have a dynamic "selector", there's no reason to manually construct RegExps like that instead of using a simple literal. Finally, the exec() method is rarely used for a few long-winded reasons; i suspect you would find "".match() or "".split() more to your liking. Commented Jul 15, 2014 at 17:25
  • Logically, the regex you build is completely equivalent to [a-z][a-z].*?([a-z][a-z]+). Your are extracting the first substring made of lower-case letters that follows two lower-case letters and one or more arbitrary characters. To me, that seems to be not exactly what you want to do. Commented Jul 15, 2014 at 17:40

3 Answers 3

7

Try this to get the second element split by the forward slashes (/):

txt.split("/")[1] 
Sign up to request clarification or add additional context in comments.

2 Comments

Other answers are correct but I like this solution better...can't believe I didn't think of this. Thanks!
-1, This way doesn't check if the format is correct (i.e. Icon/WhatYouNeedToFind/Integer.gif)
0
/\/([^\/]*)\// 

will find the first substring of non-/-characters that is surrounded by / characters.

Comments

-1

Using substring:

var get=string.substring(string.indexOf("Icon/")+5,string.indexOf("/",string.indexOf("Icon/")+5))

Where string would be Icon/anythingHere/10.gif

1 Comment

var a = string.indexOf('/'); var b = string.indexOf('/',a+1); var result = string.substr(a+1,b-a-1);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.