2011-08-08 40 views
1

我有一個字符串,這將是這個樣子:簡單的JavaScript字符串操作

I'm sorry the code "codehere" is not valid 

我需要得到字符串中的引號內的值。所以基本上我需要獲取代碼並將其存儲在一個變量中。

經過一番研究,它看起來像我可以遍歷字符串並使用.charAt(i)查找引號,然後在引號之間一次拉出一個字符。

但是我覺得必須有一個更簡單的解決方案。任何輸入將不勝感激。謝謝!

+0

這個問題可能會有一些使用 http://stackoverflow.com/questions/413071/regex-to-get-string-之間的花括號,我想要什麼之間的花括號 – Trevor

回答

3

你可以使用indexOflastIndexOf得到引號的位置:您可以驗證他們是不一樣的位置

var openQuote = myString.indexOf('"'), 
    closeQuote = myString.lastIndexOf('"'); 

然後,用substring檢索代碼:

var code = myString.substring(openQuote, closeQuote + 1); 
+0

只是在一個側面說明 - 'substring'(而不是'substr')接受開始和結束,所以它可能更直接一點:'myString.substring(openQuote, closeQuote + 1)'。 (在'substr'中+1實際上也是強制性的 - 現在它不包含最後一個''') – pimvdb

+1

完美!我不知道我是否足夠清楚我所要求的用其他答案來判斷,但這是我正在尋找的。謝謝! –

+0

如果字符串是這樣的'我很抱歉代碼「codehere」無效,「codethere」是有效的' – ShankarSangoli

1

試試這個:

var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid"; 
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1")); 
+1

你的正則表達式包含一個錯誤。 – Tomalak

+0

如果沒有符合該模式的內容,該怎麼辦?那麼整個字符串將被返回? –

2

正則表達式:

var a = "I'm sorry the code \"codehere\" is not valid"; 
var m = a.match(/"[^"]*"/ig); 
alert(m[0]); 
0

使用正則表達式!您可以使用簡單的正則表達式,例如/"(.+)"/與Javascript RegExp()對象找到匹配項。詳情請參閱w3schools.com

+0

w3schools包含很多錯誤,我不會建議使用它。 – pimvdb

+1

你可能不應該推薦w3schools。他們的很多材料都是誤導性的,有時甚至是不正確的。見.. http://w3fools.com/ –

1

您可以使用Javascript的match函數。它需要一個正則表達式作爲參數。例如:

/\".*\"/

0

試試這個:

var msg = "I'm sorry the code \"codehere\" is not valid"; 
var matchedContent = msg.match(/\".*\"/ig); 
//matchedContent is an array 
alert(matchedContent[0]); 
0

您應該使用Regular Expression。這是一種內置於JavaScript語言中的文本模式匹配器。正則表達式如下所示:/thing to match/flags *例如/"(.*)"/,它匹配一組引號之間的所有內容。

請注意,正則表達式是有限的 - 它們不能匹配嵌套的東西,所以如果引號內的值本身包含引號,那麼最終會產生一個很大的醜陋混亂。

*:或new RegExp(...),但使用字面語法;它更好。

0

你總是可以使用.split()字符串函數:

var mystring = 'I\'m sorry the code "codehere" is not valid' ; 
var tokens = [] ; 
var strsplit = mystring.split('\"') ; 
for(var i=0;i<strsplit.length;i++) { 
    if((i % 2)==0) continue; // Ignore strings outside the quotes 
    tokens.push(strsplit[i]) ; // Store strings inside quotes. 
} 

// Output: 
// tokens[0] = 'codehere' ;