Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values from string using jquery or javascript

I have string like this:-

var src=url("http://localhost:200/assets/images/eyecatcher/6/black6.png)"

And now I want to get image name i.e black6.png and folder name 6. I know there is substr function I can use but the file name and folder name will be dynamic like orange12.png and 12 etc.

How I can get these values? Please help me.

Thanks

like image 299
user3819192 Avatar asked Aug 18 '14 12:08

user3819192


People also ask

How do you get a specific value from a string in JavaScript?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do you grab substring after a specific character jQuery or JavaScript?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

Which method converts a given value into a string jQuery?

Which method converts a given value into a string in jQuery? The String() method converts a value to a string.


2 Answers

You can use split method for this:

var src = "http://localhost:200/assets/images/eyecatcher/6/black6.png";
var parsed = src.split( '/' );
console.log( parsed[ parsed.length - 1 ] ); // black6.png
console.log( parsed[ parsed.length - 2 ] ); // 6
console.log( parsed[ parsed.length - 3 ] ); // eyecatcher

etc.

like image 82
antyrat Avatar answered Sep 20 '22 02:09

antyrat


If the base URL is always the same you could do

var url = "http://localhost:200/assets/images/eyecatcher/6/black6.png";
var bits = url.replace("http://localhost:200/assets/images/eyecatcher/", "").split("/");
var folder = bits[0], // 6
    file = bits[1];  // black6.png
like image 31
Charleshaa Avatar answered Sep 21 '22 02:09

Charleshaa