Home > Software design >  String method to SELECT first 7 character and add color
String method to SELECT first 7 character and add color

Time:12-21

I have object:


const works = {
 0: ['item1', 'Step 1: first sentence here'],
 1: ['item2', 'Step 2: second sentence here'],
 2: ['item3', 'Step 3: third sentence here'],
}


I am ignoring item1, item2, item3, I selected just second array Step1: .... I am using Object.value() method

 const content = Object.values(works)
 const [value, setValue] = useState(0)
 console.log(content[value][1])

I want to select Step1: (first 7 chars) and add class / color. Is it possible? I am using this code to select first 7 characters and separate it from other

{        <p className='w-50 con fs-5'>
            {
                 // I want to add class / color to first 7 characters, is it possible? 
            content[value][1].substring(0,7).toUpperCase()   
            content[value][1].slice(7)
            }
         </p>
}

CodePudding user response:

Wrap the parts of the sentence that need their own colour in their own span with a class reference. To do this you'll need to divide the string at the first element of each nested array into substrings which you can do with slice.

I've used a separate Paragraph component in this example.

// Iterate over the array of nested arrays
// with `map` passing in each first element of the
// nested array as a text property to a paragraph component
function Example({ config }) {
  return (
    <section>
      {config.map(arr => <Para text={arr[1]} />)}
    </section>
  );
}

// Accept the text property
function Para({ text }) {

  // `slice` up the string into two parts
  const first = text.slice(0, 7).toUpperCase();
  const second = text.slice(7);

  // Build a paragraph using spans to indicate
  // which parts should be in colour
  return (
    <p>
      <span className="red">{first}</span>
      <span>{second}</span>          
    </p>
  );
}

const config = [
  ['item1', 'Step 1: first sentence here'],
  ['item2', 'Step 2: second sentence here'],
  ['item3', 'Step 3: third sentence here']
];

ReactDOM.render(
  <Example config={config} />,
  document.getElementById('react')
);
.red { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related