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.
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.
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
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/
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"