在 SVG 中如何使用 regex 进行匹配替换操作 All In One
在 SVG 中如何使用 regex 进行匹配替换操作 All In One
svg & regex
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://regexper.com/#%2F^<svg\s%5Cw%5Cs*%3E%24%2Fi
// const reg = /^<svg\s*\w*\s*>$/i;
// 匹配任意字符 (\s*\S\s*)* 或 [\s\S]* ???
const reg = /^<svg(\s*\S\s*)*>/i;
let svgStr = `<svg width="930px" height="471px" viewBox="0 0 930 471" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
reg.test(svgStr);
svgStr.replace(reg, `<svg width="100%" height="100%" viewBox="0 0 1000 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`);
js 正则表达式匹配任意字符
SVG
svg = `<?xml version="1.0" encoding="UTF-8"?>
<svg width="930px" height="471px" viewBox="0 0 930 471" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 53 (72520) - https://sketchapp.com -->
<title>test</title>
</svg>`;
viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 100">`;
xml = /<\?xml[\s\S]*\?>/i;
result = ``;
result = svg.replace(xml,``);
console.log(`\nresult`, result);
index = result.indexOf(`>`);
console.log(`\nindex`, index);
result = result.substr(index + 1);
console.log(`\nresult`, result);
result = viewport + result;
console.log(`\nviewport=\n`, result);
// console.log(`\n%cviewport=\n`, `color: red;`, result);
// 思路:??? first "> ??? index
/*
1. replace xml
2. indexOf > ??? first
*/
https://repl.it/@xgqfrms/svg-regex
XML
reg = /[\s\S]*(^<svg(\s*\S\s*)*>$)/i;
str = ` <?xml version="1.0" encoding="UTF-8"?>
<svg width="930px" height="471px" viewBox="0 0 930 471" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 53 (72520) - https://sketchapp.com -->
<title>test</title>
</svg>`;
reg.test(str);
// true
abc = str.replace(reg, `<svg width="100%" height="100%" viewBox="0 0 1000 100">`);
// str.replace(reg, `<svg width="100%" height="100%" viewBox="0 0 1000 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`);
console.log(`abc`, abc);
r = /^[\s\S]*<svg(\s*\S\s*)*>$/i;
s = `xml <svg xxx> xyz`
a = s.replace(r, `<svg width="100%" height="100%" viewBox="0 0 1000 100">`);
console.log(`a`, a);
error
OK
demos
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12299588.html
未经授权禁止转载,违者必究!