Reputation: 899
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 ° F. For more details?
I only want to get img tag and the number 84. Any suggestion? Thanks
Upvotes: 1
Views: 488
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 ° 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"
See a working example using this code:
Upvotes: 2
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 ° F. For more details?';
var src = root.firstChild.src; //the src
var number = +root.firstChild.nextSibling.nodeValue.match( /\d+/ )[0]; //84
Upvotes: 1
Reputation: 4536
You can use Regular Expressions to specify exactly what you want to look for in a string.
Upvotes: 0