简体   繁体   English

用正则表达式变量操作替换Javascript字符串

[英]Javascript string replace with regex variable manipulation

How do I replace all instances of digits within a string pattern with that digit plus an offset. 如何用该数字加上偏移量替换字符串模式中所有数字实例。

Say I want to replace all HTML tags with that number plus an offset 假设我想用该数字加上偏移量替换所有HTML标记

strRegEx = /<ol start="(\d+)">/gi;
strContent = strContent.replace(strRegEx, function() {
                                                  /* return $1 + numOffset; */
                                                   });

@Tomalak is right, you shouldn't really use regex's with HTML, you should use the broswer's own HTML DOM or an XML parser. @Tomalak是正确的,您不应真正将正则表达式与HTML一起使用,而应使用浏览器自己的HTML DOM或XML解析器。
For example, if that tag also had another attribute assigned to it, such as a class, the regex will not match it. 例如,如果该标签还分配了另一个属性,例如一个类,则正则表达式将与之不匹配。
<ol start="#" > does not equal <ol class="foo" start="#"> . <ol start="#" >不等于<ol class="foo" start="#">
There is no way to use regexes for this, you should just go through the DOM to find the element you are looking for, grab its attributes, check to see if they match, and then go from there. 没有办法使用正则表达式,您应该只通过DOM查找所需元素,获取其属性,检查它们是否匹配,然后再从那里去。

function replaceWithOffset(var offset) {
    var elements = document.getElementsByTagName("ol");
    for(var i = 0; i < elements.length; i++) {
       if(elements[i].hasAttribute("start")) {
           elements[i].setAttribute("start", parseInt(elements[i].getAttribute("start")) + offset);
       }
    }
}

the replace function obviously doesn't allow that, so doing what you need required a bit more effort 替换功能显然不允许这样做,因此您需要做的事情需要更多的精力

executing (with .exec()) a global regex multiple time will return subsequent results until no more matches are available and null is returned. 多次执行(使用.exec())全局正则表达式将返回后续结果,直到没有更多匹配可用并返回null为止。 You can use that in a while loop and then use the returned match to substring the original input and perform your modifications manually 您可以在while循环中使用它,然后使用返回的匹配项将原始输入子字符串化并手动执行修改

 var strContent = "<ol start=\\"1\\"><ol start=\\"2\\"><ol start=\\"3\\"><ol start=\\"4\\">" var strRegEx = /<ol start="(\\d+)">/g; var match = null while (match = strRegEx.exec(strContent)) { var tag = match[0] var value = match[1] var rightMark = match.index + tag.length - 2 var leftMark = rightMark - value.length strContent = strContent.substr(0, leftMark) + (1 + +value) + strContent.substr(rightMark) } console.log(strContent) 

note: as @tomalak said, parsing HTML with regexes is generally a bad idea. 注意:正如@tomalak所说,用正则表达式解析HTML通常是一个坏主意。 But if you're parsing just a piece of content of which you know the precise structure beforehand, I don't see any particular issue ... 但是,如果您只解析一部分内容,而您事先已经知道这些内容的确切结构,那么我看不到任何特定的问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM