2014-02-23 34 views
-3

我試圖做的是有這樣的事情查找字符串多次出現的JavaScript

string = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time' 

擁有的所有「'發現並放入數組。

位置我現在有格式錯誤,該代碼試圖用兩個變量來找到兩個點上使用.slice()大致是這樣的

function quoteslice(com) { 
    if (com.indexOf('"') !== -1) { 
     slicepoint1 = com.indexOf('"'); 
     com = com.slice(0,slicepoint1 + 1); 
     slicepoint2 = com.indexOf('"'); 
     com = com.slice(0, slicepoint2); 
     return com; 
    } else { 
     return com; 
    } 
} 
+1

你有沒有試圖自己實現這個?看起來你只是要求人們爲你做這項工作。你究竟在哪裏遇到問題? – Lix

+0

你有沒有嘗試過任何東西 - 說分裂http://www.w3schools.com/jsref/jsref_split.asp –

+0

剛剛找到我自己的解決方案,我需要做的(使用.split()),但那不涉及什麼首先被問到了,所以我會保持這個開放給嘗試同樣事情的人。 –

回答

1
var str = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time'; 
var res = []; 
for(var i=0; i < str.length; i++) { 
    if(str[i]==='"') { res.push(i) } 
} 

轉義字符(\)是

+1

我已經用'indexOf()'發佈了一個答案。 我非常肯定'indexOf()'更快...... – Toothbrush

+0

在Chrome的調試中測試了這一點,我必須警告未來的這個代碼的用戶要注意逃逸字符**不計數。 –

0

嘗試使用indexOf()

var string = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time'; 
var pos = 0; 
var array = []; 

while ((pos = string.indexOf("'", pos)) > -1) { 
    array.push(++pos); 
} 

否則,如果你想在str第一引號的字符串時,可以使用正則表達式:

var quotedString = str.replace(/^[\s\S]*?('.*?')[\s\S]*$/, '$1'); 
+0

試圖把這個放入一個調試器和變量'數組'不吐出任何結果 –

+0

@WhiteFusion我現在已經糾正它。 – Toothbrush

相關問題