regex for router links

I'm trying to build a navbar and since it will receive the links from a prop so it might be a router link or hyperlink which is why I want to use regex to check if the first character is / and if so then use push or else use href. however I'm getting one error. what am I doing wrong here? is my regex wrong? also is my approach correct?

error  Unnecessary escape character: \/          no-useless-escape

my code so far

<template>
  <nav>
    <ul>
      <li v-for="(item, $index) in navLinks" :key="$index">
        <router-link :to="item.link" v-if="item.link.match(reg)">{{ item.name }}</router-link>
        
        <a :href="item.link" v-else>{{ item.name }}</a>
      </li>
    </ul>
  </nav>
</template>

<script>
export default {
  name: "Navbar",
  props: {
    navLinks: {
      type: Array,
    },
  data () {
  return {
    reg: '^[\/].*' // the regex which sees if the first character is `/` or not
    }
   }
   }
</script>

the navlinks can be

const navLinks = [
  { name: "About", 
    link: "#about" },
  {
    name: "Projects",
    link: "/projects",
  },
];

#1 Answers

In vue, if you want to use a variable in the template section then you need to define it inside the data property.

data () {
  return {
    reg: '^[/].*'
  }
}

Now you can access this reg in the template section.

For the issue of the regular expression, define your regex as '^[/].*'.

Comments