2012-07-23 62 views
1

這個字符串的第N個字,該字符串是:使用正則表達式的js

one two three four five six seven eight nine ten 

你怎麼在這串選擇的第n個字?

在這種情況下,一個詞是一組一個或多個字符,可以在空格之前,成功或被空格包圍。

+2

所看到下面的答案,這是純JavaScript沒有參與任何的正則表達式要容易得多。 *必須*它使用正則表達式? – 2012-07-23 20:16:49

回答

4

儘管答案建議不要使用正則表達式,這裏有一個正則表達式的解決方案:

var nthWord = function(str, n) { 
    var m = str.match(new RegExp('^(?:\\w+\\W+){' + --n + '}(\\w+)')); 

    return m && m[1]; 
}; 

您可能需要調整表達式,以滿足您的需求。下面是一些測試用例https://tinker.io/31fe7/1

1

你可以在空間上分開,並抓住第X個元素。

var x = 'one two three four five six seven eight nine ten'; 
var words = x.split(' '); 
console.log(words[5]); // 'six' 
4

我會用split此 -

var str = "one two three four five six seven eight nine ten"; 

nth = str.split(/\s+/)[n - 1]; 
0

您可以在空間分割字符串,然後訪問它作爲一個數組:

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]); 
0
var words = "one two three four five six seven eight nine ten".split(" "); 
var nthWord = words[n]; 
當然

,你需要首先檢查第n個詞是否存在..

0
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" 
0

計算事物並不是真的應該使用正則表達式,而是嘗試根據您的分隔符(特定情況下的空格)分割字符串,然後訪問數組的第n-1個索引。

Javascript代碼:

>"one two three four".split(" "); 
["one", "two", "three", "four"] 
>"one two three four".split(" ")[2]; 
>"three" 
1
 
    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); 

其簡單:)

1

這裏是一個正則表達式,唯一的解決辦法,但我敢說,其他的答案將會有更好的表現。

/^(?:.+?[\s.,;]+){7}([^\s.,;]+)/.exec('one two three four five six seven eight nine ten') 

我把(whitespaces),句號,逗號和分號當作單詞分隔符(運行)。你可能想要適應它。 7表示Nth word - 1

有它更「動態」:

var str = 'one two three four five six seven eight nine ten'; 
var nth = 8; 
str.match('^(?:.+?[\\s.,;]+){' + (nth-1) + '}([^\\s.,;]+)'); // the backslashes escaped 

現場演示:http://jsfiddle.net/WCwFQ/2/