Brian
Brian

Reputation: 3958

Regex one-liner for splitting string at nth character where n is a variable length

I've found a few similar questions, but none of them are clean one-liners, which I feel should be possible. I want to split a string at the last instance of specific character (in my case .).

var img = $('body').attr('data-bg-img-url'); // the string http://sub.foo.com/img/my-img.jpg
var finalChar = img.split( img.split(/[.]+/).length-1 ); // returns int 3 in above string example
var dynamicRegex = '/[.$`finalChar`]/';

I know I'm breaking some rules here, wondering if someone smarter than me knows the correct way to put that together and compress it?

EDIT - The end goal here is to split and store http://sub.foo.com/img/my-img and .jpg as separate strings.

Upvotes: 1

Views: 145

Answers (2)

Lucas
Lucas

Reputation: 14949

In regex, .* is greedy, meaning it will match as much as possible. Therefore, if you want to match up to the last ., you could do:

/^.*\./

And from the looks, you are trying to get the file extension, so you would want to add capture:

var result = /^.*\.(.*)$/.exec( str );
var extension = result[1];

And for both parts:

var result = /^(.*)\.(.*)$/.exec( str );
var path = result[1];
var extension = result[2];

Upvotes: 3

Evo510
Evo510

Reputation: 173

You can use the lastIndexOf() method on the period and then use the substring method to obtain the first and second string. The split() method is better used in a foreach scenario where you want to split at all instances. Substring is preferable for these types of cases where you are breaking at a single instance of the string.

Upvotes: 0

Related Questions