简体   繁体   中英

How do I change the string value based on what it contains in react?

Let's say I want to show different copy (eg “shoes”) depending on the text in the string {variant_prod.title}

So for example:

   if (variant_prod_title == 'Nike air shoes' ) { 
        Change so "shoes" will be the only thing showing in the string
        else if (variant_prod_title == 'Nike air t-shirt' ) {
        Change so "t-shirt" will be the only thing showing in the string
    } 
        }

Here's how the code looks like for me in my react component, how do change so it only shows “shoes” for example?

<span class="uppsell-add-to-cart-copy">{variant_prod.title}</span>

This is how you can achieve this in a way that it doesn't matter if your title is 'Nike air shoes' or 'Puma shoes'. As long as it includes shoes or t-shirt the displayed value will be set accordingly.

// this sets the initial value to the entire string
let displayedValue = variant_prod.title;

// this if checks if the word e.g. 'shoes' or 't-shirt' is present in the title
if (variant_prod.title.includes('shoes')) {
    displayedValue = 'shoes';
}    
else if (variant_prod.title.includes('t-shirt')) {
    displayedValue = 't-shirt';
}

return (
    <span class="uppsell-add-to-cart-copy">{displayedValue}</span>
)

A simple way to implement what you are looking for is by using Conditional (ternary) operator

It's a good practice to use strict comparison "===" and declare your comparisons in a variable.

You can try the following code by using ES6:

 const NIKE_AIR_SHOES = 'Nike air shoes'; const NIKE_AIR_TSHIRT = 'Nike air t-shirt'; <span class="uppsell-add-to-cart-copy"> {variant_prod.title === NIKE_AIR_SHOES? "Shoes": variant_prod.title === NIKE_AIR_TSHIRT? "t-shirt": ""} </span>

You can also use the Logical AND (&&) as well as the Logical OR (||) operator to implement this.

 <span class="uppsell-add-to-cart-copy"> {(variant_prod.title === NIKE_AIR_SHOES && "Shoes") || (variant_prod.title === NIKE_AIR_TSHIRT && "t-shirt") || ""} </span>;

If your title has consistent structure and always have the output as the third value in the string then you can simply use

<span class="uppsell-add-to-cart-copy">{variant_prod.title.split(' ')[2]}</span>

variant_prod.title.split(' ') will convert the title into an array of 3 elements and you can use whatever value you want

'Nike air shoes' will return shoes

'Nike air t-shirt' will return t-shirt

'Nike air anything-else' will return anything-else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM