3

I have a route/URL :

Ex. http://localhost:8080/qr-codes

I want to access to the first segment

qr-codes

How do I do that ?

I used to be able to do sth like this in Laravel

Request::segment(1);

2 Answers 2

2

Using URL.pathname and String#split:

const str = 'http://localhost:8080/qr-codes';

const firstSegment = (new URL(str)).pathname.split('/')[1];

console.log(firstSegment);

Vue demo:

new Vue({
  el: "#app",
  computed: {
    path: function() {
      const firstSegment = (new URL(window.location.href)).pathname.split('/')[1];
      return `${firstSegment}/create`;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">{{path}}</div>

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

14 Comments

Is there a one-line way ? I will just prepend this to my create button.
Ex. /qr-codes/create
The first segment need to be dynamic ... I am passing that in as a prob.
@code8888 you can group them as above.
Can you provide more context on what you're trying to do?
|
2
const getUrlPathSegments = () => (
  (new URL(window.location.href)).pathname.split('/').filter(Boolean)
)

for example, when you call the function on current stackoverflow page, you get:

getUrlPathSegments() === ['questions', '70427242', 'vuejs-accessing-specific-url-segment']

getUrlPathSegments()[0] === 'questions'

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.