2014-01-25 28 views
1

我們如何能夠動態地在兩個指定值之間的字符串內搜索和保存子字符串。 例如,如果a有以下一組字符串。動態搜索字符串中兩個點之間的子字符串

var string1 = "This is.. my ..new string"; 
var string2 = "This is.. your ..new string"; 

我們做什麼,如果我想保存subsrting是兩個點之間,「我」和「你」在這種情況下,從字符串,也許在另一個變量或可能由除去除一切「我的」。我知道可以使用indexof(「我的」),但這不會是動態的。

+2

你應該學習如何使用正則表達式。這正是你需要的。 – TwilightSun

+0

@thefourtheye是的,我正在模式練習,總是會有兩個點... –

+1

正則表達式就是你要找的。不要使用下面的「拆分」解決方案。 – Coxer

回答

2

正則表達式是解決這類問題的方法。你可以做一些谷歌。那裏有很多文件和教程。

對於特定的問題,得到的字符串之間「」,你可以使用下面的代碼

var match1 = string1.match('\\.\\.\\s*(.+?)\\s*\\.\\.'); 
match1 = match1 ? match1[1] : false; 
var match2 = string2.match('\\.\\.\\s*(.+?)\\s*\\.\\.'); 
match2 = match2 ? match2[1] : false; 
+0

'match()'後直接使用'[]'是一個壞主意,因爲它假定匹配成功。 – Utkanos

+1

@Utkanos謝謝你的建議,我會修復 – TwilightSun

+0

@TwilightSun,這是給我的結果,我正試圖理解你做了什麼。我在正則表達式很弱 –

0

試試這個腳本:d

/* I have escaped the dots | you can add the spaces in the delimiter if that is your delimiter like*/ 
var delimiter = '\\.\\.'; 
var text = "This is.. your ..new ..test.. string"; 

/* this will match anything between the delimiters and return an array of matched strings*/ 
var res = text.match(new RegExp(delimiter + '(.*?)' + delimiter,'g')); 


/*res will be [' your ', 'test'] */ 
/* I just realized that it does not match "..new ..", which should be a valid match. */; 

/* to remove the delimiter string from your results */ 
for(i in res) { 
    res[i]=res[i].replace(new RegExp(delimiter,'g'),''); 
}; 
console.log(res); 
相關問題