Skip to content
Advertisement

Regex to replace number in url

Similar to many questions such as Javascript Regex url replace

But I’m trying to replace a number in a URL string i.e.

filename.replace('org/*/','org/23/')

The URL is much longer, but I just need to replace the number that comes after org/

ie. assets/org/1/course/154/805597a6-9c35-4f13-af83-ebfdcb12f769/upload_87bf778b-44ee-4a39-8765-ee9c4b9f3126.jpg

Advertisement

Answer

The current regex you’re passing is being interpreted as a string. You need to use the forward-slashes or RegExp class to indicate you’re passing a regex

let filename = "assets/org/1/course/154/805597a6-9c35-4f13-af83-ebfdcb12f769/upload_87bf778b-44ee-4a39-8765-ee9c4b9f3126.jpg"
console.log(filename.replace(/org/([0-9]+)//,'org/23/'))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement