How to Replace the Shortest Regex Matches in JavaScript

Replacing the shortest matching regular expression (RegEx) in a JavaScript string is helpful when you want to perform a complicated search and replace function on some text. A regular expression describes patterns in a string by using a formal language of special characters and meanings that a parser can interpret. The JavaScript "replace" function lets you specify a search string, a RegEx pattern and a replacement string. The "?" character tells the parser to find the shortest length matches.

Instructions

    • 1

      Open JavaScript code in a text editor such as Windows Notepad.

    • 2

      Create and initialize a JavaScript variable to store the string you want to search by adding the following code to the JavaScript function:

      var str="-a----b----b-----b";

    • 3

      Call the JavaScript "replace" function and display its results by adding the following code to the JavaScript function:

      document.write(str.replace(/a(.*?)b/,"xx"));

      The "/a(.*?)b/" argument specifies zero or more characters located within "a" and "b" characters. The "?" character signifies a non-greedy search, such that it should match the shortest length string that qualifies. The example will display "-xx----b-----b." Without the "?" character it would return the longest qualifying match and display "-xx."

    • 4

      Save the file. Upload it to your server and load the page to execute the "replace" function.

Related Searches:

References

Comments

Related Ads

Featured