2011-02-23 32 views
0

我有一個形式,有名稱以這種格式輸入文本字段: sometext [234] [sometext]使用JavaScript來拆分此字符串「文本[99] [文]」

喜歡的東西<input type="text" name="user[2][city]" />

我需要獲得具有拆分功能的'user','2'和'city'。

謝謝

+0

檢查,如果這個工程http://stackoverflow.com/questions/1493407/how-to-split-a-string-in-javascript – 2011-02-23 18:30:44

回答

5

我想正則表達式在這裏更合適。

var res = document.getElementsByTagName('input')[0].getAttribute('name').match(/^(\w+)?\[(\d+)?\]\[(\w+)?\]$/); 

console.log(res[1]); // === "user" 
console.log(res[2]); // === "2" 
console.log(res[3]); // === "city" 
+0

我寧願看到一個ID被添加比猜測只有一個輸入元素。 :P – Shaz 2011-02-23 18:34:25

+0

@Shaz:的確如此。我只是希望OP能夠以某種方式查詢元素。這僅僅是爲了演示。 – jAndy 2011-02-23 18:35:46

+0

我正在尋找Reg exp路徑,這是完美的謝謝。 – MatterGoal 2011-02-23 18:40:20

3
>>> "user[2][city]".split(/[\[\]]+/) 

返回此陣:

["user", "2", "city", ""] 
+0

問題在於,如果由於某種原因第一個數字值爲空,它將會分割成'['user','city','']'。 – jAndy 2011-02-23 18:48:55

1

你有沒有使用正則表達式?試試這個樣本(available in jsFiddle):

var re = /(.+?)\[(\d+)\]\[(.+?)\]/; 
var result = re.exec("user[2][city]"); 
if (result != null) 
{ 
    var firstString = result[1]; // will contain "user" 
    var secondString = result[2]; // will contain "2" 
    var thirdString = result[3]; // will contain "city" 
    alert(firstString + "\n" + secondString + "\n" + thirdString); 
}