简体   繁体   中英

Get a substring from a string using a wildcard in javascript

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.

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('/') ); 

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM