Pasan Fernando
Pasan Fernando

Reputation: 13

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?

Upvotes: 0

Views: 177

Answers (3)

Keith Nicholas
Keith Nicholas

Reputation: 44316

you can do it with a regex like :-

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

Upvotes: 0

Anthony Chu
Anthony Chu

Reputation: 37550

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

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

you could use split(), like:

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

Upvotes: 2

Related Questions