0

It's much easier to show the Javascript code than offer a complex explanation:

var html = '<input tabindex="1" type="text">';
html.replace(/tabindex="([0-9]+)"/g, 'tabindex="' + ("$1" * i) + '"');

In this code, "$1" will always be a string, meaning this RegExp will always result in 'tabindex="NaN"' ... Using parseInt doesn't work.

Is it possible to cast the response from the RegExp as an integer so I can perform maths on the replacement?

4
  • CMS and outis have given you your answer. Just out of curiosity, what are you attempting to do with this code? Commented Feb 1, 2010 at 7:46
  • I have a block of HTML being cloned within the DOM, and want to ensure the attributes are correctly updated once cloned. Simple stuff, and the above is a further simplification, as a better example. Commented Feb 1, 2010 at 7:52
  • As outis said, then, you should definitely consider cloneNode and not HTML string hacking. Then you can use simple assignments like newelement.tabindex= oldelement.tabindex*i, and you don't have to worry about exact HTML formats (eg. IE's innerHTML returning you tabindex=2 without any quotes). The only gotcha is that in IE (oh, IE, again, how we love you), assigning the name attribute has some wrinkles. Commented Feb 1, 2010 at 15:26
  • This is a very specific case where a larger chunk of HTML, (lots of elements), is available as a string in the JS, rather than in the DOM. It's way quicker to use a simple search and replace or RegExp rather than to create the element and then trawl through the various child nodes and update them - I wrote the DOM manipulation first but clocked it about 10 x as slow within Firebug, hence looking to improve the speed. Commented Feb 3, 2010 at 2:55

1 Answer 1

4

The replacement argument can be a function:

html.replace(/tabindex="([0-9]+)"/g, function (all, tabindex) {
        return 'tabindex="' + (tabindex * i) + '"'
    });

However, you should only be using regexps to manipulate HTML if you don't have a parser. If this code is to run in a browser, then you have a parser. If the node is coming from another document, use document.importNode. If the node is in the same document, use Node.cloneNode. Both support deep copying.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.