What Regular Expression to parse a URL

Asked

Viewed 510 times

6

Well, I’m asking because I don’t know, but I’m trying...

Doubt

http://www.meusite.com.br/busca.html?nome=louvor+a+Deus

Where: ?nome=louvor+a+Deus

Should be removed or better replaced with the method replace(); the symbols by spaces, are they:

? = +

I have the table RegeX for consultation at hand, but I am somewhat lay still on the subject.

  • Is this an exercise or does it have some practical purpose? I mean, replace + by spaces is not treating a URL. It seems to me that you want to access a URL parameter, so the question would be: "how to access the value of a URL parameter that is encoded?" Also, just handling spaces is not enough. Try putting special characters in this search and see what happens.

1 answer

10


In this case we are not checking a full URL, only what was requested, if it was a URL would be much more complex, even to ask the question...

Try it like this boss :

var str = 'http://www.meusite.com.br/busca.html?nome=louvor+a+Deus'
str = str.replace(/\?|=|\+/g,' ')
alert(str)

If you like it, you adapt...

Following the suggestion of the master @Randrade, I will explain, in regex:

The bars(Slash) "/" at the beginning and end "/" delimit the expression.

The backslashed (backslash) "" bars are meant to escape special characters (?,+), as they all have a function in regex, but how we want to use them literally has to escape with a " backslash.

Vertical bars "|", represent ,"or"...

And the "g" at the end is a flag, makes coincide the same occurrence several times, as in the case of "+", it is only declared once.

Here you teach some moms, Aurelio.net

Browser other questions tagged

You are not signed in. Login or sign up in order to post.