right to it:
I have a words
string which has two words in it, and i need to return the last word. They are seperated by a " ". How do i do this?
function test(words) { var n = words.indexOf(" "); var res = words.substring(n+1,-1); return res; }
I've been told to use indexOf
and substring
but it's not required. Anyone have an easy way to do this? (with or without indexOf
and substring
)
To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.
Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
Try this:
you can use words with n word length.
example:
words = "Hello World"; words = "One Hello World"; words = "Two Hello World"; words = "Three Hello World";
All will return same value: "World"
function test(words) { var n = words.split(" "); return n[n.length - 1]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With