Mohammad Efazati
Mohammad Efazati

Reputation: 4920

find special text from string in javascript

I have string like #ls/?folder_path=home/videos/

how i can find last text from string? this place is videos

other strings like

Upvotes: 0

Views: 132

Answers (7)

Yeameen
Yeameen

Reputation: 833

If the last word always enclosed with forward slashes, then you can try this -

".+\/([^\/]+)\/$"

or in regex notation

/.+\/([^\/]+)\/$/

Upvotes: 0

S L
S L

Reputation: 14328

If it always ends with / then this will works.

var str = '#ls/?folder_path=home/videos/';
var arr = str.split('/');
var index = arr.length-2;
console.log(arr[index]);

Upvotes: 0

KooiInc
KooiInc

Reputation: 122956

There are many ways to do this. One of them:

var str = '#ls/?folder_path=home/videos/'.replace(/\/$/,'');
alert(str.substr(str.lastIndexOf('/')+1)); //=> videos

Alternative without using replace

var str = '#ls/?folder_path=home/videos/'
   ,str = str.substr(0,str.length-1)
   ,str = str.substr(str.lastIndexOf('/')+1);
alert(str); //=> videos

Upvotes: 1

stema
stema

Reputation: 93026

\/([^\/]*)\/?$

This regex will match all non / between the last two /. Where the last / is optional. The $ is matching the end of the string.

Your resulting string is then in the first capturing group (because of the ()) $1

You can test it here

Upvotes: 1

James Kyburz
James Kyburz

Reputation: 14493

This will work even if the string doesn't end in / var str;

var re = /\w+(?=\/?$)/;

str = "#ls/?folder_path=home/videos/"
str.match(re) ; //# => videos

str = "#ls/?folder_path=home/videos/test/testt/"
str.match(re) ; //# => testt

str = "#ls/?folder_path=seff/test/home/videos/"
str.match(re) ; //# => videos


str = "#ls/?folder_path=home/videos/test/testt"
str.match(re) ; //# => testt

Upvotes: 1

Alex
Alex

Reputation: 66012

We could use a few more example strings, but based off of your one and only example, here's a rough regex to get you started:

.*?/\?.*?/(.*?)\//

EDIT:

Based on your extended examples:

.*?/\?.*/(.*?)\//

This regex will consume text until the second to last / and capture until the last / in the string.

Upvotes: 3

DhruvPathak
DhruvPathak

Reputation: 43265

If your data is consistent like this string, this is a simple split based way to retreive your required string: http://jsfiddle.net/EEkLP/

var str="#ls/?folder_path=home/videos/";
var strArr = str.split("/");
alert(strArr[strArr.length-2]);

Upvotes: 0

Related Questions