0

I use this to dynamically place the system variable of URL as the class on the body. The problem is that it strips the first trailing '/' and replaces it with a hyphen, which is annoying.

How could I prevent this and just replace the first '/' with nothing?

VB

<body class="<%=Request.ServerVariables("URL").Replace(".aspx","").Replace("/","-")%>">

At the moment if I use:

<body class="<%=Request.ServerVariables("URL").Replace(".aspx","").Replace("/","")%>">

I get something like 'userprofileedit' from a URL of /user/profile/edit

What I actually want is 'user-profile-edit' as a class on my body instead of 'userprofileedit'. My first example:

<body class="<%=Request.ServerVariables("URL").Replace(".aspx","").Replace("/","-")%>">

Does what I need, however I then get a starting hyphen due to the first / from '/user..' - hope this better explains my problem.

3
  • Add the '/' back on afterwards? Commented Jun 25, 2015 at 15:10
  • Updated to try explain a little more Commented Jun 25, 2015 at 15:21
  • Is the / the first character? You could remove it: Request.ServerVariables("URL").Replace(".aspx","").Remove(0, 1) I would highly suggest you put that logic in a function. Commented Jun 25, 2015 at 15:25

2 Answers 2

2

You can use Substring(1) to get everything but the first character:

<body class="<%=Request.ServerVariables("URL").Substring(1).Replace(".aspx","").Replace("/","-")%>">

Note: The approach of using Replace to remove the .aspx from the page would also remove it from a folder if it would happen to contain that, but as long as you are aware of that and don't name the folders that way, you're safe.

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

2 Comments

Is this technically a better way of doing it over the .remove() method above?
@Mat-visual: The difference is very small, but the Substring method is a bit simpler as it gets one part of the string, while the Remove method concatenates two parts of the string (the part before and after the range that you specify).
0

Use the Remove function to strip off the first character:

<body class="<%=Request.ServerVariables("URL").Replace(".aspx", "").Replace("/", "-").Remove(0, 1)

Comments

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.