// str 是 svg 中的 path,将其中的颜色(fill=\"color\"),按照顺序替换成 newColor 中的对应项
let str = \"<path d=\\\"M571.904 297.984l215.552 181.248s22.528-171.52-57.344-192-158.208 10.752-158.208 10.752z\\\" fill=\\\"#F4CE26\\\" /><path d=\\\"M250.88 876.032c-15.36-8.704-20.48-28.16-11.776-43.52l28.16-48.128c8.704-15.36 28.16-20.48 43.52-11.776 15.36 8.704 20.48 28.672 11.776 43.52l-28.16 48.128c-8.704 15.36-28.672 20.48-43.52 11.776z m235.52 34.816c-15.36-8.704-20.48-28.16-11.776-43.52l48.128-83.456c8.704-15.36 28.16-20.48 43.52-11.776 15.36 8.704 20.48 28.672 11.776 43.52l-48.128 83.456c-8.704 15.36-28.16 20.992-43.52 11.776z\\\" fill=\\\"#3F65FF\\\" /><path d=\\\"M458.752 297.984c73.216 0 139.264 44.032 167.424 111.616l13.824 33.792 36.352 5.12c52.224 7.68 91.648 52.224 91.648 105.472 0 58.88-47.616 106.496-106.496 106.496H234.496c-47.104 0-85.504-38.4-85.504-85.504 0-43.52 32.768-80.384 76.288-84.992l46.08-4.608 9.728-45.056c18.432-81.92 93.184-142.336 177.664-142.336m0-64c-117.248 0-215.552 82.432-239.616 193.024-81.92 8.704-141.312 81.92-133.12 163.84 8.192 76.288 72.192 133.632 148.48 133.632h426.496c94.208 0 170.496-76.288 170.496-170.496 0-86.016-64-157.184-146.944-168.96-36.352-88.576-123.904-151.04-225.792-151.04z\\\" fill=\\\"#333333\\\" /><path d=\\\"M937.472 512c-6.144 16.384-24.576 25.088-40.96 18.944l-39.936-14.336c-16.384-6.144-25.088-24.576-18.944-40.96 6.144-16.384 24.576-25.088 40.96-18.944l39.936 14.848c16.384 5.12 24.576 23.552 18.944 40.448z m-361.984-276.48c-15.872 7.68-34.816 0.512-42.496-15.36l-17.92-38.912c-7.168-15.872-0.512-34.816 15.36-42.496 15.872-7.68 34.816-0.512 42.496 15.36l17.92 38.912c7.68 16.384 0.512 35.328-15.36 42.496z m183.296-106.496c16.384 6.144 25.088 24.576 18.944 40.96l-14.336 39.936c-6.144 16.384-24.576 25.088-40.96 18.944-16.384-6.144-25.088-24.576-18.944-40.96l14.336-39.936c6.144-16.384 24.576-25.088 40.96-18.944z m168.448 154.624c7.168 15.872 0.512 34.816-15.36 42.496l-38.912 17.92c-15.872 7.68-34.816 0.512-42.496-15.36-7.168-15.872-0.512-34.816 15.36-42.496l38.912-17.92c15.872-7.68 35.328-1.024 42.496 15.36z m-295.424 22.528c20.48-5.12 41.472-3.584 61.44 3.584 45.568 16.896 72.704 61.44 69.632 107.52 21.504 15.872 38.4 35.84 50.688 59.392 1.024-3.072 2.56-5.632 3.584-8.704 32.256-88.576-13.312-186.368-101.888-218.624-49.152-17.92-100.864-11.264-142.848 12.8 22.016 11.776 41.984 26.624 59.392 44.032z\\\" fill=\\\"#333333\\\" />\"

let reg = /fill=\"(\\S*)\"/g
let i = 0
let newColor = [\'color1\', \'color2\', \'color3\', \'color4\', \'color5\']
let newStr = str.replace(reg, () => {
    const newfill = `fill=\"${newColor[i]}\"`
    i += 1
    return newfill
})
console.log(newStr)

我写的这个 i=0; i++ 感觉怪怪的…

相关文章

2 thoughts on “js 正则替换

发表评论

电子邮件地址不会被公开。 必填项已用*标注