-2

I have this string "Accept terms and conditions" and by design I need to replace part of that string with span tags, that is, "terms" and "conditions" should be wrapped with span like <span>terms</span> and <span>conditions</span>. To find solution I have found How to add color to a specific part of a string in React using replace? but it does not work as expected. So, I have FormInput component which is used like this:

<FormInput
          type="checkbox"
          value={formik.values.terms}
          name="terms"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          label={`Accept terms and conditions`}
          checkbox={true}
        >
          {formik.touched.terms && formik.errors.terms ? (
            <ErrorMessage termsCheckbox={true}>
              {formik.errors.terms}
            </ErrorMessage>
          ) : null}
        </FormInput>

As you can see I am passing label={Accept terms and conditions} and I need to ensure that the words 'terms' and 'conditions' are in red color

2
  • Please post your code so we can get a better idea of how to help you. Commented Jan 20, 2021 at 18:15
  • @imstupidpleasehelp, done, I have added react component I hope it is clearer now if not pls let me know Commented Jan 20, 2021 at 18:21

1 Answer 1

0

If I understand your question correctly, the following approach can be followed.
you can use regular expression for this purpose. Find the match in your string and replace them with desired pattern using the result from respective capturing groups.

var str = 'accept terms and conditions'
var regex = /(terms)|(conditions)/g

var res = str.replace(regex,function(match,p1,p2){
   if(p1) return `<span>${p1}</span>`
   else if (p2) return `<span>${p2}</span>`
})
console.log(res)

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

Comments

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.