Skip to content
Advertisement

Get the last word of a string

I have tried a few things to get a last part out I done this:

JavaScript

The first one won’t work and the second returns an array but a realy need string.

Advertisement

Answer

If you’re after the last word in a sentence, why not just do something like this?

JavaScript

I wouldn’t recommend using regular expressions as it’s unnecessary, unless you really want to for some reason.

JavaScript

Using a substr() method would be better than both of these if resources/efficiency/overhead is a concern.

JavaScript

it is faster, although it really doesn’t make that much of a difference on things like this. If you’re constantly needing to know the last word on a 100,000 word string, you should probably be going about it in a different way.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement