javascript标记化器

javascript tokenizer

本文关键字:javascript      更新时间:2024-02-05

我有一个关于在javascript中拆分字符串的问题。我从其他地方得到一个字符串,我只想得到它的一部分。我不能使用substr,因为它的长度可以更改。我也看了拆分方法,但这还不够。例如,我的一个字符串如下:

<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。有什么建议吗?感谢

这是应该使用正则表达式的地方。

你可以做一些类似的事情:

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/

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

您可以使用正则表达式来指定要在字符串中查找的内容。