2011-10-05 56 views
0

下面是一個例子字符串:我如何獲得字符串的某個部分?

survey_questions_attributes_1317784471568_answers_attributes 

我想獲得1317784471568出字符串的。

但是這部分也可以是文本。例如,我可能還需要從字符串中的同一位置獲取一個名爲new_questions的字符串。

這裏的常數是survey_questions_attributes_將始終位於我想要的塊之前,並且_answers_attributes將始終跟隨它。

回答

2
id = str.match(/_questions_attributes_(.+)_answers_attributes/)[1]; 
2
var str = "survey_questions_attributes_1317784471568_answers_attributes"; 

var newStr = str.replace("survey_questions_attributes_", ""); 
newStr = newStr.replace("_answers_attributes", ""); 

我能想到的最簡單的方法,而不使用正則表達式或類似的東西。

1

嘗試 -

var text = "survey_questions_attributes_1317784471568_answers_attributes" 
     .replace("survey_questions_attributes_","") 
     .replace("_answers_attributes","") 
-1

使用字符串():

mystring = "survey_questions_attributes_1317784471568_answers_attributes" 
newstring = mystring.substring(28, 41) 
+0

這需要的東西被發現是一個恆定的長度,這可能是一個不正確的假設。 – Joe

+0

喬是正確的,字符串將不會是一個恆定的長度。 – Shpigford

+0

原始問題指出數字周圍的字符串是「常量」。 –

相關問題