Reputation: 19688
for this, the string is:
one two three four five six seven eight nine ten
how do you select the nth word in this string?
a word in this case is a group of one or more characters, either preceded, succeeded, or surrounded by a whitespace.
Upvotes: 1
Views: 5770
Reputation: 22508
Despite the answers suggesting to not use regular expressions, here's a regex solution:
var nthWord = function(str, n) {
var m = str.match(new RegExp('^(?:\\w+\\W+){' + --n + '}(\\w+)'));
return m && m[1];
};
You may have to adjust the expression to fit your needs. Here are some test cases https://tinker.io/31fe7/1
Upvotes: 5
Reputation: 26022
Here is a Regex-only solution, but I daresay the other answers will have a better performance.
/^(?:.+?[\s.,;]+){7}([^\s.,;]+)/.exec('one two three four five six seven eight nine ten')
I take (runs of) whitespaces, periods, commas and semicolons as word breaks. You might want to adapt that. The 7
means Nth word - 1
.
To have it more "dynamic":
var str = 'one two three four five six seven eight nine ten';
var nth = 8;
str.match('^(?:.+?[\\s.,;]+){' + (nth-1) + '}([^\\s.,;]+)'); // the backslashes escaped
Live demo: http://jsfiddle.net/WCwFQ/2/
Upvotes: 1
Reputation: 1109
function getWord(str,pos) { var get=str.match(/\S+\S/g); return get[pos-1]; } //Here is an example var str="one two three four five six seven eight nine ten "; var get_5th_word=getWord(str,5); alert(get_5th_word);
Its simple :)
Upvotes: 2
Reputation: 1558
Counting things is not really what you should use a regex for, instead try maybe splitting the string based on your delimiter (space in your specific case) and then accessing the n-1th index of the array.
Javascript code :
>"one two three four".split(" ");
["one", "two", "three", "four"]
>"one two three four".split(" ")[2];
>"three"
Upvotes: 0
Reputation: 50787
var nthWord = function(str, n) {
return str.split(" ")[n - 1]; // really should have some error checking!
}
nthWord("one two three four five six seven eight nine ten", 4) // ==> "four"
Upvotes: 0
Reputation: 5145
var words = "one two three four five six seven eight nine ten".split(" ");
var nthWord = words[n];
of course, you need to check first that the nth word exists..
Upvotes: 0
Reputation: 38416
You can split the string on spaces, and then access it as an array:
var sentence = 'one two three four five six seven eight nine ten';
var exploded = sentence.split(' ');
// the array starts at 0, so use "- 1" of the word
var word = 3;
alert(exploded[word - 1]);
Upvotes: 0
Reputation: 19475
I would use split
for this -
var str = "one two three four five six seven eight nine ten";
nth = str.split(/\s+/)[n - 1];
Upvotes: 4
Reputation: 227200
You could just split on the spaces, and grab the Xth element.
var x = 'one two three four five six seven eight nine ten';
var words = x.split(' ');
console.log(words[5]); // 'six'
Upvotes: 1