在javascript中使用replace时,属性不应替换

时间:2018-08-01 12:38:25

标签: javascript jquery

当我用其他内容替换内容时,属性也会替换。意味着如果您在下面检查此URL,则需要将文本“ my_text”替换为“ Mark”。现在,此替换(但包括该替换)的锚属性“ my_text”也将替换。因此,我只需要替换属性以外的内容。

var src_str = $("#test").html();
var term = "mY_text";
term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("("+term+")", "gi");

src_str = src_str.replace(pattern, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");

$("#test").html(src_str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">this is <a href="mY_text" >my</a> text that needs highlighting my_text</div>

2 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么您想在字符串“ my_text”出现在文本内容中时替换它,而不是在属性中出现时替换它。

这是一个很好的例子,说明为什么用regex操作HTML不是一个好主意:regex不知道DOM节点与属性和文本之间的区别。而是使用DOM遍历方法来查找要修改的DOM部分,并仅在这些部分上工作:

// contents() includes text nodes, which is what we want to search through here:
$('#test').contents().each(function() {
  // If you were just replacing text, you could simply set this.textContent 
  // to a new value. But since it looks like you're trying to insert 
  // a DOM node, we need to convert the text node into a DOM node:
  if (this.textContent.indexOf('my_text') > -1) { // there's a match 
    var replacementNode = document.createElement('span'); 
    // the regex can be simple here, because we know we're working only with text:
    var newContent = this.textContent.replace(/(my_text)/,'<mark>$1</mark>'); 
    replacementNode.innerHTML = newContent;
    // ... and then replace the text node with the new DOM node:
    this.parentNode.insertBefore(replacementNode,this);
    this.parentNode.removeChild(this)
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">this is <a href="my_text" >my</a> text that needs highlighting my_text</div>

(以上内容仅作用于#test元素的直接子元素。如果您需要在DOM树中进行更深入的搜索,则可以使用one of the methods shown here遍历树并查找文本节点,然后将上述代码应用于这些元素。)

答案 1 :(得分:0)

如果要更改文本内容,请使用let translateVar = [0,0]; let scaleVar = 1; let radius = 50; function create_pan_zoomable_svg(html_element, width, height) { let svg = d3.select("body") .append("svg") .attr("width", "100%") .attr("height", "100%") .style("background-color", "#eeeeee") .call(_zoom).on("dblclick.zoom", null) .append("g"); d3.select("#zoom_in").on('click', function() { _zoom.scaleBy(svg, 2)}); d3.select("#zoom_out").on('click', function() { _zoom.scaleBy(svg, 0.5)}); create_marker(svg); initialize_link_node(svg); return svg; } var _zoom = d3.zoom() .on("zoom", function() { translateVar[0] = d3.event.transform.x; translateVar[1] = d3.event.transform.y; scaleVar = d3.event.transform.k; svg.attr('transform', 'translate(' + translateVar[0] + ',' + translateVar[1] + ') scale(' + scaleVar + ')'); }); function create_marker(svg) { let defs = svg.append("defs"); defs.append("marker") .attr("id", "arrow") .attr("viewBox", "0 -5 10 10") .attr("refX", 40) .attr("refY", 0) .attr("markerWidth", 8) .attr("markerHeight", 8) .attr("orient", "auto") .append("svg:path") .attr("d", "M0,-5L10,0L0,5"); } function getScreenInfo() { return { width : ($(window).width()-translateVar[0])/scaleVar, height : ($(window).height()-translateVar[1])/scaleVar, centerx : (($(window).width()-translateVar[0])/scaleVar)/2, centery : (($(window).height()-translateVar[1])/scaleVar)/2 }; } let link, node, simulation; function initialize_link_node(svg) { let currentScreen = getScreenInfo(); simulation = d3.forceSimulation() .force("link", d3.forceLink() .id(function(d) { return d.id; })) .force("charge", d3.forceManyBody() .strength(function(d) { return -20000;})) .force("center", d3.forceCenter(currentScreen.centerx, currentScreen.centery)); link = svg.append("g").selectAll(".link"); node = svg.append("g").selectAll(".node"); } function spawn_nodes(svg, graph, around_node, filtering_options) { node = node.data(theData.nodes, function(d) { return d.id; }); let newNode = node.enter().append("g"); newNode = newNode.append("circle") .attr("class", "node") .attr("r", radius) .attr("fill", function(d) { return colors[d.type] }) .attr("id", function(d) { return d.id }); /**************************************************** newNode.append("text") .text( function(d) { return d.id; }) .style("fill", "red") .style("text-anchor", "middle"); newNode.append("svg:image") .attr("href", function(d) { return dict_type_icon[d.type]; }).attr("width", "30") .attr("height", "30");**************************/ newNode.call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended) ); node = node.merge(newNode); link = link.data(theData.edges, function(d) { return d.id; }); let newLink = link.enter().append("line").attr("class", "link").attr("marker-end", "url(#arrow)"); newLink.append("title").text(function(d) { return d.labeled; }); link = link.merge(newLink); node = node.merge(newNode); simulation.nodes(theData.nodes).on("tick", ticked); simulation.force("link").links(theData.edges); simulation.alpha(1).alphaTarget(0).restart(); } function dragstarted(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } function dragged(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } function ticked() { let currentScreen = getScreenInfo(); node .attr("cx", function(d) { return d.x = Math.max(radius, Math.min(currentScreen.width - radius, d.x)); }) .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(currentScreen.height - radius, d.y)); }); link .attr("x1", function(d) {return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); }

如果要更改$('a').text('your new text'),请使用href

两者之间没有关系。