Search code examples
regexasp-classicreplacesublimetext2

An advanced Find and Replace with RegEx in Sublime Text


I have a directory full of Classic ASP legacy code, and almost all files have something similar to this:

<input type="hidden" name="driverPayment" value="<% =driverPayment %>">

Then later in the code, some JavaScript is running, and doing the following:

var x = document.getElementById('driverPayment')

This works fine in IE, but of course doesn't work anywhere else because there is no ID attribute defined.

The fix is to go through the 1770 files and manually add an ID attribute that matches the name property on the input. So make it like so:

<input type="hidden" name="driverPayment" id="driverPayment" value="<% =driverPayment %>">

Is there a way I can automate this process by using the logic below:

  1. Get input element with a name attribute
  2. If input has id attribute, move to next input
  3. Else add an ID attribute to the input, and give it a name matching the value of the name attribute

I'd like to do this for the 1770 Classic ASP files I have. I am using Sublime Text.


Solution

  • You can use regex to match. My regex isn't great but the following should work. Happy for others to improve on it. I used some regex from this question.

    Right Click project folder

    Choose "Find in folder" option

    Find and replace options appear at bottom of screen. Select the regex option (far left).

    regex-find-and-replace

    Enter

    <(?:input)\s+(?=[^>]*\bname\s*=)(?![^>]*\bid\s*=)[^>]*>?(name="driverPayment")
    

    in Find field

    Enter

    id="driverPayment" name="driverPayment" 
    

    in Replace field

    Click Replace