简体   繁体   中英

how to select a some characters from string in javascript

I have a url strings like "example.com/Apps/Visitor/visitscanner" , "example.com/Apps/Seatings/visitscanner

i want to select the directory name after the "" http://example.com/Apps/ "

for above example url's, if my url string is " http://example.com/Apps/Visitor/visitscanner " this one, then results should be like "Visitor".

How can i do this in javascript?

you could use split() , like:

var str = "example.com/Apps/Visitor/visitscanner";
var parts = str.split('/');
console.log( parts[parts.length - 2] ); //Visitor

You can do this with regex if you want to match URLs like "http://example.com/Apps/Visitor/visitscanner/foo" or "http://example.com/Apps/Visitor" ...

var url = "http://example.com/Apps/Visitor/visitscanner";
var match = /^(https?:\/\/)?example.com\/apps\/([^/]+)/i.exec(url);
var directory = match[2]; // get the second match group ("Visitor")

Live Demo

you can do it with a regex like :-

var url = "http://example.com/Apps/Visitor/visitscanner";
var dirName  = /\/\/.+?\/Apps\/(.+?)(?=\/)/g.exec(url)[1];

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