0

I am trying to replace the filepath with just the filename using regex, and struggling.

I take a list of text like this:

xlink:href="file://C:\x\y & DRAWINGS\z - CONTROLLED\a \testsvg-A01.svg"

and i just want to output

xlink:href="testsvg-A01.svg"

I can get there with separate regex (javascript) with several bits of regex as such:

let inQuotes = hrefs[0].match(/"(.*?)"/gm);
inQuotes = inQuotes[0].match(/([^\\]+$)/gm);
inQuotes = inQuotes[0].replace(/"/g, "");

this will return just the filename, but i was wondering if there was a way to take this and replace the original text to the desired style.

EDIT:

i can get it for a single occurrance with this line of code:

let testHrefs = outText.match(/xlink:href="(.*?)"/gm)[0].match(/"(.*?)"/gm)[0].match(/([^\\]+$)/gm)[0].replace(/^/, 'xlink:href="');

but it looks awful and doesn't completely do what i want. Any advice?

2 Answers 2

1

You could use a regex to remove the text you don't want to keep (i.e. everything between the href=" and the filename:

let href = 'xlink:href="file://C:\\x\\y & DRAWINGS\\z - CONTROLLED\\a \\testsvg-A01.svg"';
console.log(href);
console.log(href.replace(/href=".*?([^\\\/]+)$/, 'href="$1'));

Note I've used [\\\/] to allow for Unix and Windows style filenames, if you only want Windows style filenames that can simply be [\\].

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

2 Comments

Thanks! this is great. Is there a way i can do this for multiple lines though? ie. if there is a list of hrefs in text, can i change them all in this format?
I just did a string.split and replaced every specific line, this worked wonders. Thanks a bunch Nick!
1

First, keep in mind that backslashes in strings need to be escaped, as the backslash itself is an escape character. You'll likely want to escape these as \\.

After doing this, you can make use of a positive look-behind on the \ with the regex (?<=\\)[^\\]*:

var xlink = "file://C:\\x\\y & DRAWINGS\\z - CONTROLLED\\a \\testsvg-A01.svg";
var regex = /(?<=\\)[^\\]*/gm;
console.log(xlink.match(regex));

This splits the string into each of the folders (which may be useful within itself), though if you exclusively want the filename, you can use xlink.match(regex)[4] (assuming the length is consistent), or xlink.match(regex)[xlink.match(regex).length - 1] if it isn't.

var xlink = "file://C:\\x\\y & DRAWINGS\\z - CONTROLLED\\a \\testsvg-A01.svg";
var regex = /(?<=\\)[^\\]*/gm;
console.log(xlink.match(regex)[xlink.match(regex).length - 1]);

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.