2

I have a little problem with my code:

<template slot="popover">
  <img :src="'img/articles/' + item.id + '_1.jpg'">
</template>

Some of my item.id numbers have a slash in them. As a result, some images are not displayed. Now I would like to replace the slash with an underline or delete it, if a slash occurs in the item.id numbers. Is there a simple solution for this?

The slash should only be replaced at this point in the code and not in another place where the item.id is used.

3
  • use a function to handle this inside like: <img :src="'img/articles/' + handleSlash(item.id) + '_1.jpg'"> Commented Dec 10, 2021 at 11:42
  • which vue version are you using? Commented Dec 10, 2021 at 11:43
  • I am using version 16.11.1 Commented Dec 10, 2021 at 12:07

2 Answers 2

5

you can use a computed property and replace slashes by dashes with replace and a regex:

<template slot="popover">
  <img :src="`img/articles/${itemId}_1.jpg`">
</template>

<script>
...
  computed: {
    itemId: function(){
        return this.item.replace(/\//g, '-');
    }
  }
...
</script>

here's a test fiddle : https://jsfiddle.net/pqfvba6n/

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

2 Comments

I use dashes in my example, but you can use any other character like underscores like this this.item.replace(/\//g, '_') or remove slashes like this this.item.replace(/\//g, '')
I use :src="`img/articles/${itemId}_1.jpg`" instead of :src="'img/articles/' + itemId + '_1.jpg'" because I found it cleaner, but you can keep your version
0

Use replace (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

<template slot="popover">
  <img :src="'img/articles/' + item.id.replace(/\//g, '_') + '_1.jpg'">
</template>

2 Comments

if there are many slashes, it will only replace the first, that's why I use a regex with g flag
The question mentions "slash" not "slashes", so should be covered with .replace("/", "_") Although i did edit my answer to use regex, thanks

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.