【问题标题】:replace part of string with html tags in react在反应中用html标签替换部分字符串
【发布时间】:2021-01-20 18:14:37
【问题描述】:

我有这个字符串“接受条款和条件”,根据设计,我需要用跨度标签替换该字符串的一部分,也就是说,“条款”和“条件”应该用像<span>terms</span>和@987654323这样的跨度包装@。为了找到解决方案,我找到了How to add color to a specific part of a string in React using replace?,但它没有按预期工作。所以,我有这样使用的 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} 并且我需要确保“条款”和“条件”这两个词是红色的

【问题讨论】:

  • 请发布您的代码,以便我们更好地了解如何为您提供帮助。
  • @imstupidpleasehelp,完成,我已经添加了反应组件,如果不是,请告诉我

标签: javascript reactjs


【解决方案1】:

如果我正确理解您的问题,可以遵循以下方法。
为此,您可以使用regular expression。使用来自各个捕获组的结果,在您的字符串中找到匹配项并replace 使用所需的模式。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多