我有一个关于在javascript中拆分字符串的问题。我从其他地方得到一个字符串,我想只得到它的一部分。我不能使用substr因为它的长度可以改变。我也看了分裂法,但还不够。例如,我的一个字符串看起来像这样:
<img src="http://image.weather.com/web/common/wxicons/31/30.gif?12122006" alt="" />Partly Cloudy, and 84 ° F. For more details?
我只想获得img标签和数字84.有什么建议吗?感谢
答案 0 :(得分:2)
这是应该使用regular expressions的地方。
您可以执行以下操作:
var inputStr = '<img src="http://image.weather.com/web/common/wxicons/31/30.gif?12122006" alt="" />Partly Cloudy, and 84 ° F. For more details?';
var regex = /<img.*?src="(.*?)".*?>.*?([0-9]+\s*°\s*[CF])/;
var results = regex.exec(inputStr);
results[1]; // => "http://image.weather.com/web/common/wxicons/31/30.gif?12122006"
results[2]; // => "84 ° F"
请参阅使用此代码的工作示例:
答案 1 :(得分: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 ° F. For more details?';
var src = root.firstChild.src; //the src
var number = +root.firstChild.nextSibling.nodeValue.match( /\d+/ )[0]; //84
答案 2 :(得分:0)
您可以使用Regular Expressions准确指定要在字符串中查找的内容。