如何从Javascript中的字符串替换svg标签

时间:2018-06-29 16:34:08

标签: javascript regex

我正在尝试使用正则表达式替换字符串中的svg标签,这就是我尝试过的方法。

const REPLACE_TAGS = [
  'svg',
  'g',
  'circle',
  'path',
  'rect',
  'defs',
  'line',
  'linearGradient',
  'radialGradient',
  'stop',
  'ellipse',
  'polygon',
  'polyline',
  'text',
  'tspan'
];



const str = '<g fill="none" fill-rule="evenodd"> <path fill="none" d="M0 0h24v24H0z"/> <path stroke="#333" stroke-linecap="round" stroke-linejoin="round" d="M3.5 12.5h17v9h-17zM13.5 12.5v9M10.5 12.5v9M1.883 9.602l18.353-4.918.776 2.898L2.66 12.5z"/> <path stroke="#333" stroke-linejoin="round" d="M6 6.857c.957.553 4.675.393 4.675.393S8.957 3.945 8 3.393a2 2 0 1 0-2 3.465zM15.296 4.366c-.546.956-3.852 2.674-3.852 2.674s-.164-3.718.388-4.674a2 2 0 1 1 3.464 2z"/> <path stroke="#333" stroke-linecap="round" stroke-linejoin="round" d="M12.508 6.755l.777 2.897M9.61 7.531l.776 2.899"/> ></g>'

function recurs(str, arr, index) {
  if (index >= arr.length) {
    return str;
  }
  let tag = `<(/?)${arr[index]}\b((?:[^>"']|"[^"]*"|'[^']*')*)>`;
  let pattern = /tag/g;
  str = str.replace(pattern, `SVG.${arr[index][0].toUpperCase()}${arr[index].slice(1)}`);
  return recurs(str, arr, index + 1);
}

const strn = recurs(str, REPLACE_TAGS, 0);
console.log(strn);

正则表达式似乎不起作用,该如何解决?

1 个答案:

答案 0 :(得分:1)

主要问题是let pattern = /tag/g;。它不会从tag变量中创建正则表达式。这是一个正则表达式,用于查找字符串中的文字tag字。

您需要使用let pattern = new RegExp(tag);在其中创建一个正则表达式。

此外,您还需要对\进行两次转义

所以

const REPLACE_TAGS = [
  'svg',
  'g',
  'circle',
  'path',
  'rect',
  'defs',
  'line',
  'linearGradient',
  'radialGradient',
  'stop',
  'ellipse',
  'polygon',
  'polyline',
  'text',
  'tspan'
];



const str = '<g fill="none" fill-rule="evenodd"> <path fill="none" d="M0 0h24v24H0z"/> <path stroke="#333" stroke-linecap="round" stroke-linejoin="round" d="M3.5 12.5h17v9h-17zM13.5 12.5v9M10.5 12.5v9M1.883 9.602l18.353-4.918.776 2.898L2.66 12.5z"/> <path stroke="#333" stroke-linejoin="round" d="M6 6.857c.957.553 4.675.393 4.675.393S8.957 3.945 8 3.393a2 2 0 1 0-2 3.465zM15.296 4.366c-.546.956-3.852 2.674-3.852 2.674s-.164-3.718.388-4.674a2 2 0 1 1 3.464 2z"/> <path stroke="#333" stroke-linecap="round" stroke-linejoin="round" d="M12.508 6.755l.777 2.897M9.61 7.531l.776 2.899"/> ></g>'

function recurs(str, arr, index) {
  if (index >= arr.length) {
    return str;
  }
  let tag = `<(/?)${arr[index]}\\b((?:[^>"']|"[^"]*"|'[^']*')*)>`;
  let pattern = new RegExp(tag,'g');
  str = str.replace(pattern, `SVG.${arr[index][0].toUpperCase()}${arr[index].slice(1)}`);
  return recurs(str, arr, index + 1);
}

const strn = recurs(str, REPLACE_TAGS, 0);
console.log(strn);