0

I want to replace underscores with slashes when they are before a four digit number, for example

res_234_2010-xxx -> res_234/2010-xxx
res_12345_1999-yyy -> res_12345/1999-yyy

(In fact, the four digit number should be a valid year, startin with 19xx or 20xx)

Is there some way to achieve it with .replace method, or shall I do it programmatically?

1
  • Use a lookahead. regular-expressions.info/lookaround.html. Please show what you've tried, we can't help you fix your code if you don't first make an attempt. Commented Apr 12, 2015 at 2:33

1 Answer 1

2

You can use the following regular expression:

var result = str.replace(/_((?:19|20)\d{2})\b/g, '/$1');

Regular Expression Explanation

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

2 Comments

Great answer, I would give you extra points for adding the regex explanation
@opensas, using lookahead. var result = str.replace(/_(?=(?:19|20)\d{2}\b)/g, '/');

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.