user10828115
user10828115

Reputation:

Replace affects all strings in an array

I am having some issues about replacing. I am fetching some integers from DB. And if the number fetched is just 1 then I replace it with "empty", but when I do that, it affects all numbers that have 1 in them.

Here is what I am doing, first calling toString and then replace

<tr v-if="moreIndex < one.length"  v-for="moreIndex in morePro">
  <td>{{one[moreIndex].products}}</td>
  <td>{{priceSep(one[moreIndex].price).toString().replace("1", "empty")}}</td>
</tr>

So I am changing "1" to empty but if any other data has includes 1 then output look like this...

5empty98  

How can I fix this problem?

Upvotes: 0

Views: 45

Answers (3)

Mamun
Mamun

Reputation: 68923

You can check the length with Conditional (ternary) operator .:

<td>{{priceSep(one[moreIndex].price).toString().length == 1 ? priceSep(one[moreIndex].price).toString().replace("1", "empty") : priceSep(one[moreIndex].price).toString()}}</td>

May be, you can try directly set the value if the value is 1:

<td>{{priceSep(one[moreIndex].price).toString() == "1" ? "empty" : priceSep(one[moreIndex].price).toString()}}</td>

Upvotes: 1

Jigius
Jigius

Reputation: 315

You can use RegExp:

{{priceSep(one[moreIndex].price).toString().replace(/^1$/, "empty")}}

Upvotes: 0

brk
brk

Reputation: 50326

You can check the length of the string before replacing it

{{priceSep(one[moreIndex].price).toString().length > ? 
  priceSep(one[moreIndex].price).toString() :
  priceSep(one[moreIndex].price).toString().replace("1", "empty")
}}

Upvotes: 0

Related Questions