简体   繁体   English

在反应中用 html 标签替换部分字符串

[英]replace part of string with html tags in react

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> .我有这个字符串“接受条款和条件”,根据设计,我需要用跨度标签替换该字符串的一部分,也就是说,“条款”和“条件”应该用跨度包装,如<span>terms</span><span>conditions</span> To find solution I have found How to add color to a specific part of a string in React using replace?为了找到解决方案,我找到了如何使用替换为 React 中字符串的特定部分添加颜色? but it does not work as expected.但它没有按预期工作。 So, I have FormInput component which is used like this:所以,我有这样使用的 FormInput 组件:

<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如您所见,我正在传递 label={ Accept terms and conditions } 并且我需要确保“条款”和“条件”这两个词是红色的

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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