Tx3
Tx3

Reputation: 6916

Searching for a last word in JavaScript

I am doing some logic for the last word that is on the sentence. Words are separated by either space or with a '-' character.

What is easiest way to get it?

Edit

I could do it by traversing backwards from the end of the sentence, but I would like to find better way

Upvotes: 4

Views: 9764

Answers (6)

maerics
maerics

Reputation: 156384

Try splitting on a regex that matches spaces or hyphens and taking the last element:

var lastWord = function(o) {
  return (""+o).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lastWord('This is a test.'); // => 'test.'
lastWord('Here is something to-do.'); // => 'do.'

As @alex points out, it's worth trimming any trailing whitespace or hyphens. Ensuring the argument is a string is a good idea too.

Upvotes: 17

user578895
user578895

Reputation:

Using a regex:

/.*[\s-](\S+)/.exec(str)[1];

that also ignores white-space at the end

Upvotes: 6

Anand Thangappan
Anand Thangappan

Reputation: 3106

Well, using Split Function

  string lastWord = input.Split(' ').Last();

or

string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];

While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.

string input = ".... ,API";

here, the comma would be part of the "word".

Also, if the first method of obtaining the word is correct, ie. everything after the last space, and your string adheres to the following rules:

Will always contain at least one space
Does not end with one or more space (in case of this you can trim it)

then you can use this code that will allocate fewer objects on the heap for GC to worry about later:

string lastWord = input.Substring(input.LastIndexOf(' ') + 1);

I hope its help

Upvotes: 0

Anish
Anish

Reputation: 2917

You can try something like this...

<script type="text/javascript">
var txt = "This is the sample sentence";
spl = txt.split(" ");
for(i = 0; i < spl.length; i++){
    document.write("<br /> Element " + i + " = " + spl[i]); 
}
</script>

Upvotes: 0

Here is a similar discussion have a look

Upvotes: 0

Daveo
Daveo

Reputation: 19872

Have you tried the lastIndexOf function http://www.w3schools.com/jsref/jsref_lastIndexOf.asp

Or Split function http://www.w3schools.com/jsref/jsref_split.asp

Upvotes: 0

Related Questions