繁体   English   中英

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

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

我有这个字符串“接受条款和条件”,根据设计,我需要用跨度标签替换该字符串的一部分,也就是说,“条款”和“条件”应该用跨度包装,如<span>terms</span><span>conditions</span> 为了找到解决方案,我找到了如何使用替换为 React 中字符串的特定部分添加颜色? 但它没有按预期工作。 所以,我有这样使用的 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>

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

如果我正确理解您的问题,可以遵循以下方法。
您可以为此目的使用正则表达式 在您的字符串中找到匹配项,并使用来自各个捕获组的结果将它们替换为所需的模式。

 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