DEV Community

Cover image for Sublime 3: A Quick Tip Using Find and Replace with Regex
James Thomson
James Thomson

Posted on

Sublime 3: A Quick Tip Using Find and Replace with Regex

TL;DR

Use (.*?) to match anything in the given context.
Use \1 to replace with the matched value.

e.g.

Find: <use xlink:href="(.*?)”>
Replace: <use xlink:href="\1" href="\1">

The Long Version

Recently I discovered a bug related to how Chrome references external SVGs with the <use> tag. For whatever reason Chrome has an issue that if the SVG file isn't cached it can sometimes not render the referenced SVG. To add to the frustration, the issue seems to be intermittent.

One user on Stack Overflow suggests that because the xlink:href attribute is deprecated that using href solves the problem. So, I figured I'd give a shot, why not, right? The only problem is I use this tag all over my project so manually finding each tag and replacing the value would be a tedious task...especially without knowing if this suggestion would actually fix the issue.

Enter Sublime's find and replace with regex option.

Say I have this tag

<svg><use xlink:href="/icons/symbol-defs.svg#icon-refresh"></use></svg>
Enter fullscreen mode Exit fullscreen mode

and I need to add another attribute, but it must use the same value as the xlink:href attribute.

All I need to do is fire up Sublime's Find and Replace dialogue (Cmd+Shift+F in Mac, Ctrl+Shift+F in Windows/Linux), make sure the Regex icon is toggled on, and enter these values:

Find: <use xlink:href="(.*?)”>
Replace: <use xlink:href="\1" href="\1">

Here's what that looks like in Sublime:

Activate regex option in Sublime Find and Replace

What this does is match anything within the xlink:href attributes double quotes and copies the value to the replaced tag.

So we end up with

<svg><use xlink:href="/icons/symbol-defs.svg#icon-refresh" href="/icons/symbol-defs.svg#icon-refresh"></use></svg>
Enter fullscreen mode Exit fullscreen mode

Too easy, right? That's it, just a quick tip to make your life easier.

Happy coding! 🤓

p.s. In case you were wondering, the fix didn't work, but hey at least I learned something new, right? 😉

Latest comments (1)

Collapse
 
j_holtslander profile image
Jay Holtslander

This info helped me in that I learned of (.*?) which I didn't know about before.

I was able to do this as a result and it saved the day.

  • Find: <input value="(.*?)”>
  • Replace: <input value="CONSISTENT_VALUE_NOW”>