0

I have a string of the following format:

var str1="tag:youtube.com,2008:video:VrtMalb-XcQ";

From this I need to extract the last part i.e. VrtMalb-XcQ. How can I achieve this?

1

3 Answers 3

5

What you need to know is the index of the last :. This can be achieved by using lastIndexOf

var str1="tag:youtube.com,2008:video:VrtMalb-XcQ";
var result = str1.substr(str1.lastIndexOf(':') + 1);

The + 1 is there because otherwise you would also get the colon itself in the string.

This is really the fastest approach to do it, and requires the least memory.

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

Comments

2

use split and pop:

var str1="tag:youtube.com,2008:video:VrtMalb-XcQ";
str1.split(':').pop()

4 Comments

It is totally unnecessary to split the whole thing when all you need is the index of the last ':'
@SimonAndréForsberg ... why it's unnecessary?? it's just the simple and short solution, thats works great
It is a waste of CPU power and memory. It is doing more job than is really required (small waste, but still a waste)
As I said: It is a small waste, but still a waste. It definitely gets the job done, but it's not the most optimal way.
0
 "tag:youtube.com,2008:video:VrtMalb-XcQ".replace(/.*:/, "")

4 Comments

Using regex for this? Seriously? I don't think this is a good solution
@SimonAndréForsberg Not worth a downvote, it does work
@JuanMendes Sorry, I'm way too active on Code Review to do anything else. Additionally, there is no description at all, just a code dump.
why not regex? it's clean and simple.

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.