0

Trying to get a filename and have it return a string.

try to turn:

plate-71-winter-hawk-final.jpg

into:

winter hawk final

where plate might also be uppercase. Here is what I have so far, doesn't seem to work

var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"

var newString = theString.replace(theRegEx, theString);

newString;
4
  • Why do you need a regex to do this? You can use a combination of Substring and Replace to do this much quicker than you could have written this post. Commented Apr 1, 2016 at 0:33
  • oh, I wasn't aware. Thought regex might be easiest way? Commented Apr 1, 2016 at 0:34
  • Regex is much more complex than simple string manipulation, particularly when you're dealing with this type of operation. You don't need that complexity here. Commented Apr 1, 2016 at 0:35
  • 1
    Rule #1 to use RegEx: Look for alternatives of using RegEx. Commented Apr 1, 2016 at 0:35

2 Answers 2

2

Unfortunately, the "Rule #1" doesn't offer a better way:

var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
                         .replace(/-/g, ' ');

Take care when you use a string with the object syntax to escape backslahes:

var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');

Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]

You can write it like this too (without string):

var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Sign up to request clarification or add additional context in comments.

3 Comments

This returns winter-hawk-final. Shouldn't - be removed ?
Yes, it need to be replaced with a space.
yeah .replace(/-/g, ' '); seems to fix this, its in his example. this worked, thanks!
0

Try following script. It's not dependent on length of string as long as it follows standard pattern:

var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;

var match = rx.exec(data);
if(match != null){
   data = match[1];
   data = data.replace(/\-/g, ' ');
}

console.log(data);

It will print:

winter hawk final

Comments

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.