简体   繁体   中英

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

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.
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="#"> .
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.

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. You can use that in a while loop and then use the returned match to substring the original input and perform your modifications manually

 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. 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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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