2

I have a string like this:

dir/subdir/file-hash.ext

Knowing that the "hash" part in the above text is always 8 numbers/letters long, how can I make this string as shown below:

dir/subdir/file.ext

The only thing that may change is the string having or not a / at the beginning.

I have no idea how can i achieve this

2
  • .replace(/-\w{8}(?=\.)/, "")? Commented Sep 10, 2013 at 11:19
  • What do you mean by "hash part"? Commented Sep 10, 2013 at 11:20

2 Answers 2

4

With a regular expression :

var str2 = str1.replace(/-.{8}\.ext$/, '.ext');

If the extension may change (for example .odt instead of .txt , use

var str2 = str1.replace(/-.{8}(\.[\d\w]+)$/, '$1');
Sign up to request clarification or add additional context in comments.

1 Comment

You likely intended to escape the . before ext.
1

Since you have fixed-length you don't need to use a regular expression. Use (last)indexOf and substr.

var path = "dir/subdir/file-01234567.ext"; // or "/dir/subdir/file-01234567.ext"
var pos = path.lastIndexOf("."); // find the last `.`
path = path.substr(0, pos - 8) + path.substr(pos); // dir/subdir/file-.ext

If you want it without the trailing - use:

path = path.substr(0, pos - 9) + path.substr(pos); // dir/subdir/file.ext

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.