0

how can I split these strings so that I get the results below? I want to be able to do something like this:

 alert(img/small/Closed-Main-Fabric-Collar_2018.png.replace(/\-/g, ' '));

this would alert: Closed-Main-Fabric-Collar but I need it to work even if the sting has an extra /mid/ I'm pretty sure I will need two replace functions one to get the "Closed-Main-Fabric-Collar" and one to get the "2018"

 1. img/small/Closed-Main-Fabric-Collar_2018.png
 2. img/small/Base-Shirt_2016.jpg
 3. img/small/mid/Outside-Pocket-Left_2019.png
 4. img/small/large/Outside-Pocket-Left_2019.png


 1. Closed-Main-Fabric-Collar
    2018

 2. Base-Shirt
    2016

 3. Outside-Pocket-Left
    2019

 4. Outside-Pocket-Left
    2019

Thanks!

3
  • take subString not replace Commented Jun 17, 2013 at 7:55
  • "...this would alert: Closed-Main-Fabric-Collar..." No, not even close. Have you actually tried doing this? Commented Jun 17, 2013 at 7:58
  • yep, I know it does not work. Thats why I'm asking the question. Commented Jun 17, 2013 at 7:59

1 Answer 1

1

You can extract the two substrings you're looking for with a regular expression:

var str = "img/small/Closed-Main-Fabric-Collar_2018.png";
var match = /\/([A-Za-z\-]+)_(\d+)\.$/.exec(str);
if (match) {
    // match[1] has "Closed-Main-Fabric-Collar"
    // match[2] has "2018"
}

That regular expression breaks down like this:

  • \/ Match a literal /
  • (...) Capture the text that matches the expression within these parentheses.
  • [A-Za-z\-]+ Match one or more of the characters A-Z, a-z, and -.
  • _ Match a literal _.
  • \d+ Match one or more digits
  • \. Match a literal ..

Since there are two capture groups, they're captured in the resulting match object's [1] and [2] properties.

Sign up to request clarification or add additional context in comments.

3 Comments

I think that's left up to you, you can start here regular-expressions.info
@user2238083: You don't actually need the png part, so I've removed it above.
@user2238083: The above works with the sample data you listed in your question. If you're having trouble applying it to your code, I suggest asking a question posting your code and showing how you're trying to apply it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.