Marc Rasmussen Marc Rasmussen - 1 month ago 7
Javascript Question

Regex finding the last string that doesnt contain a number

Usually in my system i have the following string:

http://localhost/api/module


to find out the last part of the string (which is my route) ive been using the following:

/[^\/]+$/g


However there may be cases where my string looks abit different such as:

http://localhost/api/module/123


Using the above regex it would then return
123
. When my String looks like this i know that the last part will always be a number. So my question is how do i make sure that i can always find the last string that does not contain a number?

Answer
partYouWant = urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')

Here it is in action:

urlString="http://localhost/api/module/123"
urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
-->"module"

urlString="http://localhost/api/module"
urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
-->"module"

It just uses a capture expression to find the last non-numeric part. It's going to do this too, not sure if this is what you want:

urlString="http://localhost/api/module/123/456"
urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
-->"module"
Comments