2012-07-25 65 views
1

我有一個關於在javascript中分割字符串的問題。我從別的地方得到一個字符串,我只想得到它的一部分。我不能使用substr,因爲它的長度可以改變。我也看了拆分方法,但這還不夠。例如,我的一個字符串看起來像這樣:javascript tokenizer

<img src="http://image.weather.com/web/common/wxicons/31/30.gif?12122006" alt="" />Partly Cloudy, and 84 &deg; F. For more details? 

我只想獲得img標籤和數字84.任何建議?謝謝

+1

什麼是你的字符串,例如常數,是'° 「所有字符串都存在? – Sirko 2012-07-25 11:15:37

+0

只有img源,「部分多雲」和數字可以改變。休息是一樣的 – 2012-07-25 11:25:57

回答

2

這是一個應該使用regular expressions的地方。

你可以這樣做:

var inputStr = '<img src="http://image.weather.com/web/common/wxicons/31/30.gif?12122006" alt="" />Partly Cloudy, and 84 &deg; F. For more details?'; 
var regex = /<img.*?src="(.*?)".*?>.*?([0-9]+\s*&deg;\s*[CF])/; 
var results = regex.exec(inputStr); 

results[1]; // => "http://image.weather.com/web/common/wxicons/31/30.gif?12122006" 
results[2]; // => "84 &deg; F" 

使用此代碼見一個工作示例:

http://jsfiddle.net/epkcn/

+0

好的我會檢查它 – 2012-07-25 11:24:31

+0

它不會返回任何東西。我跟着你寫的 – 2012-07-25 11:48:37

+0

我已經添加了一個jsFiddle,它顯示了一個使用與上面類似的代碼的實例。我已將它添加到答案中,並將其複製到此處以方便您:http://jsfiddle.net/epkcn/ – 2012-07-25 11:54:07

1
var root = document.createElement("div"); 
root.innerHTML = '<img src="http://image.weather.com/web/common/wxicons/31/30.gif?12122006" alt="" />Partly Cloudy, and 84 &deg; F. For more details?'; 

var src = root.firstChild.src; //the src 
var number = +root.firstChild.nextSibling.nodeValue.match(/\d+/)[0]; //84