Reputation: 591
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!
Upvotes: 0
Views: 242
Reputation: 1074365
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.
Upvotes: 1