8

Can someone please help. I need to get the characters between two slashes e.g:

Car/Saloon/827365/1728374

I need to get the characters between the second and third slashes. i.e 827365

0

8 Answers 8

19

You can use the split() method of the String prototype, passing in the slash as the separator string:

const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');

// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:

const interestingPart = parts[2];

It's also possible to achieve this as a one-liner:

const interestingPart = value.split('/')[2];

Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Sign up to request clarification or add additional context in comments.

Comments

2

This will simply alert 1728374, as you want

alert("Car/Saloon/827365/1728374".split('/')[3]);

or, a bit longer, but also more readable:

var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/

Comments

0

Try the_string.split('/') - it gives you an array containing the substrings between the slashes.

Comments

0

try this:

var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element

Comments

0

Use split to divide the string in four parts:

'Car/Saloon/827365/1728374'.split('/')[2]

Gives "827365"

Comments

0

You will have to use the .split() function like this:

("Car/Saloon/827365/1728374").split("/")[2];

Comments

0
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]

How many you want you take it.. :)

Comments

-1
var str = "Car/Saloon/827365/1728374";

var items = str.split("/");

for (var i = 0; i < items.length; i++)
{
   alert(items[i]);
}

OR

var lastItem = items[items.length - 1]; // yeilds 1728374

OR

var lastItem1728374 = items[2];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.