gpt4 book ai didi

javascript - 替换某个模式的子串

转载 作者:行者123 更新时间:2023-12-04 08:35:19 27 4
gpt4 key购买 nike

<svg fill="#000075" data-icon="symbol-triangle-down" width="16" height="16" viewBox="0 0 16 16"><desc>symbol-triangle-down</desc><path d="M13 4.01c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 .16.05.31.11.44H3.1l4 8h.01c.16.33.49.56.89.56s.72-.23.89-.56h.01l4-8h-.01c.06-.14.11-.28.11-.44z" fill-rule="evenodd"></path></svg>
我想用颜色替换 fill 的值,比如 #ff0000 .请注意,字符串中的颜色值并不总是相同并且是动态的。
这就是我所拥有的:

const str = `<svg fill="#000075" data-icon="symbol-triangle-down" width="16" height="16" viewBox="0 0 16 16"><desc>symbol-triangle-down</desc><path d="M13 4.01c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 .16.05.31.11.44H3.1l4 8h.01c.16.33.49.56.89.56s.72-.23.89-.56h.01l4-8h-.01c.06-.14.11-.28.11-.44z" fill-rule="evenodd"></path></svg>`;

console.log(str.replace(/fill="{7}"/, '#ff0000'))

请指教。
最终结果应该是
const str = `<svg fill="#ff0000" data-icon="symbol-triangle-down" width="16" height="16" viewBox="0 0 16 16"><desc>symbol-triangle-down</desc><path d="M13 4.01c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 .16.05.31.11.44H3.1l4 8h.01c.16.33.49.56.89.56s.72-.23.89-.56h.01l4-8h-.01c.06-.14.11-.28.11-.44z" fill-rule="evenodd"></path></svg>`;

最佳答案



const str = `<svg fill="#000075" data-icon="symbol-triangle-down" width="16" height="16" viewBox="0 0 16 16"><desc>symbol-triangle-down</desc><path d="M13 4.01c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 .16.05.31.11.44H3.1l4 8h.01c.16.33.49.56.89.56s.72-.23.89-.56h.01l4-8h-.01c.06-.14.11-.28.11-.44z" fill-rule="evenodd"></path></svg>`;

console.log(str.replace(/(\sfill=")#[a-fA-F0-9]+(")/, '$1#ff0000$2'))

regex proof .
说明
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
fill=" 'fill="'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
# '#'
--------------------------------------------------------------------------------
[a-fA-F0-9]+ any character of: 'a' to 'f', 'A' to 'F',
'0' to '9' (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
) end of \2

关于javascript - 替换某个模式的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64827571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com