Reputation: 2129
I have a string like /test/file/sometext/public/image
and a second string /test1/file/sometext1/public/image1
.
I want to get the substring starting from file
and ending on public
.
So the first string should return file/sometext/public/
and from the 2nd string it should return file/sometext1/public/
.
In every string this file
and public
is static.
How will I do this in javascript?
Basically I need this
str = '/test/file/sometext/public/image';
var str1 = str.replace("file/sometext/public/", "");
But I need here a wildcard so that sometext can be replaces whatever text comes between file
and public
. Hope you get my point.
Upvotes: 0
Views: 578
Reputation: 67525
You could use split()
to splits a string into an array of strings, with slice()
that returns a shallow copy of a portion of an array into a new array object and finally the join()
to joins all elements of an array into a final string :
var parts = '/test/file/sometext/public/image'.split('/');
console.log( parts.slice(2, 5).join('/') );
Upvotes: 1
Reputation: 4443
You can do this by using Regular Expression.
var str = '/test/file/sometext/public/image';
var reg = /file\/[^\/]*\/public/i;
var replace = str.replace(reg, 'something');
console.log('before',str);
console.log('after',replace);
Upvotes: 0
Reputation: 337627
If all strings follow the same folder structure you can split them in to an array and rebuild it with the required parts, like this:
var arr = str = '/test/file/sometext/public/image'.split('/');
var str1 = arr[2] + '/' + arr[3] + '/' + arr[4] + '/';
console.log(str1);
Upvotes: 0