简体   繁体   中英

Remove part from string

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

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');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM