根据Javascript中的模式替换单词

Replace a word based on a pattern in Javascript

本文关键字:替换 单词 模式 Javascript 根据      更新时间:2023-09-26

我正在将SVG转换为PNG,需要删除SVG中的angularjs属性。

<rect fill="#F9B24F" ry="5" rx="5" ng-attr-y="{{node.rectY}}" ng-attr-x="{{node.rectX}}" 
  ng-attr-height="{{chart.height}}" ng-attr-width="{{chart.width}}" y="10" x="20"    
height="80" width="160">

我需要作为输出

<rect fill="#F9B24F" ry="5" rx="5"  y="10" x="20"    
height="80" width="160">

我正在尝试使用javascript中的StringReplace方法进行替换。我在控制台中尝试了以下操作,但不起作用

"ng-repeat='{{dddddsd}}' dfjdzjfhjk".replace(/ng-*'s/g," "); 

如果您可以依赖Angular属性始终ng-xyz="..."形式,您可以这样做:

str = str.replace(/'bng-[^'s]+="[^"]*"/g, '');

如果有些是单引号,您可以使用第二个replace:

str = str.replace(/'bng-[^'s]+='[^']*'/g, '');

显然,这是一个很大的"如果",但如果你想用正则表达式操纵类似SGML的标记,这是你必须具备的那种"如果"

示例:

var str = '<rect fill="#F9B24F" ry="5" rx="5" ng-attr-y="{{node.rectY}}" ng-attr-x="{{node.rectX}}" ng-attr-height="{{chart.height}}" ng-attr-width="{{chart.width}}" y="10" x="20"    height="80" width="160">';
display("Before: " + str);
str = str.replace(/'bng-[^'s]+="[^"]*"/g, '');
display("After: " + str);
function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg).replace(/&/g, "&amp;").replace(/</g, "&lt;");
    document.body.appendChild(p);
}

不要使用正则表达式来解析DOM。(关于为什么在这里的详细答案:RegEx匹配开放标签,XHTML自包含标签除外)

只需遍历DOM并剥离任何不需要的属性。

var svg = $('#mySvg').clone(); //see http://api.jquery.com/clone/
var allNodes = svg.find('*');
allNodes.each( function(i,node) {
    //Here you can extract any attribute starting with ng- but not all angular directives
    //start with ng-*
    node.removeAttribute('ng-repeat');
} );