str.replace 的用法[js]

replace 的用法

1. 简单的使用

  • str.replace(source, target)
  • 字符串 str 中,用 target 替换 source。
  • source: 源字符串中被替换的字符串。
  • target: 替换的字符串。

2. 正则匹配

  • str.replace(/source/g, cb 函数)
  • 字符串 str 中,用 cb 函数的返回值替换 source。
  • 正则匹配式末尾有 g,则多次匹配,多次进入到回调函数。

2.1 例子

//Simple
let text = "Mr Blue has a_blue b_car house and a_blue b_car";
let result = text.replace(/a_([\w\-_]+) b_([\w\-_]+)/g, (a, b, c) => {
  /**
   * a: 正则匹配到的字符串
   * b: a中捕获的第一部分([\w\-_]+) - 视正则公式而定
   * c: a中捕获的第二部分([\w\-_]+) - 视正则公式而定
   */
  return "yellow"; // 返回的值来匹配a
});
console.log("result: ", result);
//result:  Mr Blue has yellow house and yellow
  • 在查看 css to tailwindcss 中,行内样式需要进行匹配并转化成 tailwindcss 放置到原标签的 class 中。这部分有进行应用。
  • https://github.com/Simon-He95/transformToTailwindcss
const styleReg = /<([\w\-_]+)[^>]*[^:]style="([^"]+)"[^>]*>/g; // 匹配到没一个标签的整体,捕获标签名;捕获该标签的行内元素的内容。
const removeStyleReg = / style="([#\w\:\-\s;\[\]\/\+%]+)"/; // 移除掉行内元素style,转化成tailwindcss补充到class中。
let templateMatch = `
<div class="father-wrapper" size="mini" style="width: 1000px">
  <button  class="btn-wrapper" style="width:300px;background-color: pink;" size="mediumn" >
    button
  </button>
  <div />
</div>
`;
/**
 * 正则匹配末尾带g,则是多部分进行匹配,每次正则匹配到都会进入到回调函数中
 * target: 正则匹配到的局部字符串
 * tag: target的第一部分捕获的字符串 - 视正则而定
 * inlineStyle: target的第2部分捕获的字符串 - 视正则而定
 *
 */
let replaceRes = templateMatch.replace(styleReg, (target, tag, inlineStyle) => {
  let newClass = "md-100"; // inlineStyle转换后的行内元素字符串
  // 每一行更新后,都将一行带整体进行返回
  // 先移除掉行内元素的字符串再把更新后的class拼接回去;

  //【每一次更新源字符串的写法】,则不需要replaceRes了;遵循replace设计的,不修改源字符串;
  // templateMatch = templateMatch.replace(target, target.replace(removeStyleReg, '').replace(`<${tag}`, `<${tag} class="${newClass}"`))

  // 返回的值为最新的target,进行替换
  return target
    .replace(removeStyleReg, "")
    .replace(`<${tag}`, `<${tag} class="${newClass}"`);
});

console.log("templateMatch: ", templateMatch); // replace不修改原字符串
console.log("replaceRes  : ", replaceRes);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值