I have one variable holding single line string which is html element like this.
var des = "<p> --Sometext before-- FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
I want to select everything after FI: until comma sign into one variable and after comma sign until
tag into another variable. Also for SE: and EN: too.
For example, result will be like this.
var fi_name = "This is fi name";
var fi_manufacturer = "This is fi manufacturer";
var se_name = "This is se name";
var se_manufacturer = "This is se manufacturer";
var en_name = "This is en name";
var en_manufacturer = "This is en manufacturer";
Note, the string change dynamically but still have same pattern.
For example:
<p> --Sometext before-- FI:[name],[manufacturer]<br/ >SE:[name],[manufacturer]<br/ >FI:[name],[manufacturer]</p>
You can have a look at demo in JsFiddle.
Now it's throwing null error.
Edited v v v
It's not working in live website. The des variable is fully look like this. Please see http://jsfiddle.net/AM8X2/ It's throwing null again.
You can just look for the specified pattern and extract the relevant information from there:
var des = "<p>FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
var f = function(w, s) {
return new RegExp(w + ':([^,]+)').exec(s)[1];
}
fi = f('FI', des);
se = f('SE', des);
en = f('EN', des);
w + ':([^,]+)'
can be explained as: get me the value after the colon of w
in s
here is the updated fiddle.
A more complete solution, one that handles all HTML tags would be the following:
var f = function(w, s) {
var el = document.createElement('div'), arr;
el.innerHTML = s;
arr = (new RegExp(w + ':([^\n]+)').exec(el.innerText)[1]).split(',');
return {
manufacturer: arr[1],
name: arr[0]
}
}
fi = JSON.stringify(f('FI', des));
se = JSON.stringify(f('SE', des));
en = JSON.stringify(f('EN', des));
The fiddle for this is here
To access any of these in variables (without the JSON.stringify()
, the direct method return, i.e. f('SE', des)
), you would do:
// for fi manufacturer
fi.manufacturer
// for en name
en.name
// etc..
in my opinion, by using this, you have a much more modular approach, and less chance of error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With