2

I am trying to replace a segment of a path in a string with another string. I have a feeling that RegEx would be the best way to do this but don't know how. I would like to replace xxxxx with another string:

resources/audio/xxxxx/someaudio.mp3

The root path of "resources/audio/" will always remain the same, but I am trying to replace the parent folder of the audio file. The audio file is arbitrary and can change. Can someone please help?

2 Answers 2

3

You may try this:

var newFolder = "yyyy";
var r = "resources/audio/xxxxx/someaudio.mp3".replace(/(resources\/audio\/).*(\/.*)/g, '$1' + newFolder + '$2');
console.log(r);

See it working here.

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

Comments

0

Use replace method with capturing group:

> 'resources/audio/xxxxx/someaudio.mp3'.replace(/\bxxxxx\/([^/]+)$/, 'yyyy/$1')
"resources/audio/yyyy/someaudio.mp3"
> 'resources/audio/xxxxx/anotheraudio.mp3'.replace(/\bxxxxx\/([^/]+)$/, 'yyyy/$1')
"resources/audio/yyyy/anotheraudio.mp3"

([^/]+) match filename and captured as group 1. This group 1 is referenced as $1 in replacement string.


Or use positive lookahead:

> 'resources/audio/xxxxx/someaudio.mp3'.replace(/\bxxxxx(?=\/[^/]+$)/, 'yyyy')
"resources/audio/yyyy/someaudio.mp3"
> 'resources/audio/xxxxx/anotheraudio.mp3'.replace(/\bxxxxx(?=\/[^/]+$)/, 'yyyy')
"resources/audio/yyyy/anotheraudio.mp3"

2 Comments

Why do you use the capturing group? Would it work to just replace the directory name by itself (i.e., 'path/to/file.mp3'.replace(/\/to\//, 'the'))?
@andyg0808, What if /to/ is occur twice? I used capturing group/lookahead to match only the parent directory of the file.

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.