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
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)
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.