Ahmet Tanakol
Ahmet Tanakol

Reputation: 899

javascript tokenizer

I have a question about splitting string in javascript. I'm getting a string from somewhere else and I want to get only a part of it. I can't use substr because its length can be altered. I also looked at split method, but it is not enough also. For example, one of my strings looks like this:

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

I only want to get img tag and the number 84. Any suggestion? Thanks

Upvotes: 1

Views: 488

Answers (3)

Jon Newmuis
Jon Newmuis

Reputation: 26522

This is where one should use regular expressions.

You can do something like:

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"

See a working example using this code:

http://jsfiddle.net/epkcn/

Upvotes: 2

Esailija
Esailija

Reputation: 140228

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

Upvotes: 1

chrisfrancis27
chrisfrancis27

Reputation: 4536

You can use Regular Expressions to specify exactly what you want to look for in a string.

Upvotes: 0

Related Questions