esvnt
esvnt

Reputation: 101

How to make specific number of characters change color?

I'm making a Karuta web game. In karuta, there are "kimariji", which are the minimum amount of "letters" needed to know which card to take. These counts will be stored in the API/JSON I've created, which get saved as a state and read from.

I'm looking to do this: (english example)

var kimarijiCount = 6
string = 'Elephant'
in this case, only 'Elepha' turns red.

var kimarijiCount = 2
string = 'Rhino'
in this case, only 'Rh' turns red.

How can I do this using javascript/react? I'm assuming my pseudocode would be:

//get string
//get count variable x
//set css for the first x chars to a different colour 

This is how my code for creating the cards current looks, if it helps

    render() {      
if (this.props.displayType === "kanji") {
        return (
            <div id="CardContainer" className="cardContainer">
                {this.props.cards.slice(0, this.props.number).map((cards, index) => (
                    <div id="card" className="cardOuter" onClick={() => this.props.handleComp(index)}>
                        <div className="cardInner">
                            <p key={index}>{cards.back}</p>
                        </div>
                    </div>
                ))}

            </div>)
    }

Upvotes: 3

Views: 828

Answers (2)

Ismail H Rana
Ismail H Rana

Reputation: 371

You can use const, let, or var for text_color, which helps you to customize and change color property.

// var kimarijiCount = 2
// var str = 'Rhino'

const text_color = { color: 'red' };

let res = str.substring(0, kimarijiCount);
let rest = str.substring(kimarijiCount, str.length);

<span style= { text_color }> { res } </span> { rest };

kimarijiCount must be limited to str.length

Upvotes: 0

Sam Gomena
Sam Gomena

Reputation: 1479

Here's a sandbox that should work for the example you gave!

In short, you probably want to use slice on your kimariji:

// Slice the first `kimarjiCount` characters of kimarji and make them red
<span color={{ color: "red" }}>{kimarji?.slice(0, kimarjiCount)}</span>

// Append the rest of the kimarji
<span>{kimarji?.slice(kimarjiCount, kimarji.length)}</span>

This uses the optional chaining operator to ensure that the kimarji variable exists before calling slice on it.

Upvotes: 1

Related Questions