I have a string which is inside the HTML code.
here, I need to get a string separately using javascript.
outsidePara
and
insidePara
var msg="<p><sp id='msgId'>insidePara</sp>outsidePara</p>"
Is the <p> always in the same format (i.e. will always have a ```
If so, jQuery's $('p sp#blablabla') should be able to help as you can then select the text of the parent <p> and trim off the <sp>
var sender = $('p sp#blablabla').text()
var msg = $('p sp#blablabla').parent('p')
var msgHTML = msg.html()
var msgBody = msgHTML.substr(msg.length - (9 + sender.length)); // 9 for the two <sp> tags
const cheerio = require('cheerio')
const $ = cheerio.load(`<p><sp id=\"blablabla\">puppy</sp>hi</p>`)
console.log($("p sp").text()) // will print puppy
console.log($("p").contents().last().text()) // will print hi
Related
Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.
I have an online store that has limited access to make any correct edits to code.
I am trying to implement proper Price Schema as they have:
<span itemprop="price">$57.00</span>
This is incorrect.
It needs to be set up like this
<span itemprop="priceCurrency" content="USD">$</span>
<span itemprop="price">57.00</span>
Is there something in JavaScript or jQuery that can manipulate this by separating the Currency Symbol and Price?
Thanks
You get the ELEMENT text:
var value = $("span[itemprop='price'").text();
Then you could generate the html using regex like:
var html = '$57.00'.replace(/([^\d])(\d+)/,
function(all, group1, group2){
return 'some html here =' + group1 + '= more hear =' + group2 });
Might not be 100% bug-free, but it should get you started:
<script type="text/javascript">
var n = document.getElementsByTagName('*')
for(var i=0;i<n.length;i++)
{
if(n[i].hasAttribute('itemprop')) //get elements with itemprop attribute
{
var p = n[i].parentNode
var ih = n[i].innerHTML //grab the innerHTML
var num = parseFloat(ih) //get numeric part of the innerHTML - effectively strips out the $-sign
n[i].innerHTML = num
//create new span & insert it before the old one
var new_span = document.createElement('span')
new_span.innerHTML = '$'
new_span.setAttribute('itemprop', 'priceCurrency')
new_span.setAttribute('currency', 'USD')
p.insertBefore(new_span, n[i])
}
}
</script>
Somthing along the lines of
// find all span's with itemprop price
document.querySelectorAll("span[itemprop='price']").forEach(function(sp){
// grab currency (first char)
var currency = sp.innerText.substr(0,1);
// remove first char from price val
sp.innerText = sp.innerText.substr(1);
// create new element (our price-currency span)
var currencySpan = document.createElement("span");
currencySpan.innerText = currency;
currencySpan.setAttribute("itemprop", "priceCurrency");
currencySpan.setAttribute("content", "USD");
// Append it before the old price span
sp.parentNode.insertBefore(currencySpan, sp);
});
Should do what your after.
See demo at: https://jsfiddle.net/dfufq40p/1/ (updated to make effect more obvious)
This should work -- querySelectorAll should be a bit faster, and the regex will work with more than just USD, I believe.
function fixItemPropSpan() {
var n = document.querySelectorAll('[itemprop]');
for (var i = 0; i < n.length; i++) {
var p = n[i].parentNode;
var ih = n[i].innerHTML;
var num = Number(ih.replace(/[^0-9\.]+/g, ""));
n[i].innerHTML = num;
//create new span & insert it before the old one
var new_span = document.createElement('span');
new_span.innerHTML = '$';
new_span.setAttribute('itemprop', 'priceCurrency');
new_span.setAttribute('currency', 'USD');
p.insertBefore(new_span, n[i]);
}
}
Here is a suggestion of how you can make this work, though i would not suggest doing it like this (too many cases for content="").
Example of the logic you could use to transform the incorrect format to the correct one.
Hope you find it useful. :]
I have scoured Google looking for an answer but I cant seem to find one.
I need to split the following string into separate variables
the string is stored as a variable
:-
var location = autocomplete.getPlace();
var address = location['formatted_address'];
Output:-
<span class="street-address">Street address</span>, <span class="locality">Town</span>, <span class="region">County</span> <span class="postal-code">Post Code</span>, <span class="country-name">Country</span>
eg.
var street = "Street address";
var town = "Town";
var county = "County";
var postc = "Post Code";
var country = "Country";
So I need to get the contents between
<span class="street-address"></span>
<span class="locality"></span>
etc...
Sometime there are extra spans sometimes less.
I have looked at some javascript but it only gets the content between:-
<span class="locality"> and the very last </span>
Any help in the right direction would be greatly
Are you using plain javascript? or jQuery?
in javascript you can get the text inside an element via:
var1 = document.getElementByClass("street-address").innerText
or in jQuery:
var streetAddress = $('.street-address').text();
var city= $('.city').text();
If you're using jQuery:
var 1 = $('span.street-address').text();
var 2 = $('span.locality').text();
var 3 = $('span.region').text();
var 4 = $('span.postal-code').text();
var 5 = $('span.country-name').text();
It should be that simple, unless I am missing something in the question.
Can you use jQuery? Check this out https://jsfiddle.net/zsxar4r4/
var address = [];
$('span').each(function(idx, span) {
address.push($(span).html());
})
console.log(address);
You can use the getElementsByClassName() method, which will return an array-like object.
https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName
var addressData = document.getElementsByClassName('address');
//And than do something with the object. You can access it like an array:
console.log(addressData[2].innerHTML);
In my HTML file I have this snippet of code:
<textarea class="form-control" id="textfield" rows="10"></textarea>
And in my Javascript file I have this:
input1 = document.getElementById('input1').value;
input2 = document.getElementById('input2').value;
textfield = document.getElementById('textfield');
if(document.getElementById('tmkbSelect').value == "option1") {
document.getElementById('tmkb').innerHTML = "Tafel";
for(input2i=0;input2i<20;input2i++){
document.getElementById('textfield').value = input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i;
}
}
I'm basically trying to create a multiplication table. It works, but not quite.
The javascript code is in a function and I call that function using a button, but the problem is that the output is this:
3 * 19 = 57
I want it to be:
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
And so on, how do I do this?
I need to do this using only Javascript.
You need to concatenate the strings and then put them in the textarea.
You can add the strings to an array, and then concatenate them after the loop and put them in the textarea:
var lines = [];
for(input2i=0;input2i<20;input2i++){
lines.push(input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i);
}
document.getElementById('textfield').value = lines.join('\n');
Use ShortHand operator for adding content to textarea.
document.getElementById("test").value += "\n 1";
Demo
In the loop, you assign the value:
... .value = input1+...
That means you overwrite the content every time. You need to append instead:
var content = '';
...
content += input1+...
...
document.getElementById('textfield').value = content;
Note the +=.
Don't forget to add '\n' after each line or everything will be in one line.
If I write code 2 without code 1, the code works and it shows me “aaaaa”.
But if I write code 1 and code 2, the code doesn’t work. Instead of showing me “vvvaa”, it doesn’t show me anything (not “aaaaa” and not “vvvaa”).
Why doesn’t it work? (The document.getElementById doesn’t send the information to the <div>.)
Code 1:
document.getElementById('na').innerHTML = "vvvaa";
Code 2:
document.write("<div id='na'> aaaaa </div>");
Complete Code: (the only thing on the page)
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
timeago('1376743609');
document.write("<div id='na'> aaaaa </div>");
</script>
Order matters. You cannot access your element 'na' before having it in the document.
You naturally need to add the element to the document first. If that's done, you can access it by functions like getElementById().
This...
document.write("<div id='na'></div>");
document.getElementById('na').innerHTML = "vvvaa";
... will work.
You may shortcut this to:
document.write("<div id='na'>vvvaa</div>");
I am assuming your console says that document.getElementById('na') is undefined and innerHTML is not a method of undefined. This is caused by the fact that there is no such element when the code is called. A fatal error will stop any further javascript execution, in this case your document.write.
Add the element to your document first before trying to access it via document.getElementById
You can't access a piece of text unless it really does exist. In your case, you are trying to access the text when it doesn't even exist at that point. The order matters. Code 2 should go first and Code 1 should go last. First write the text, then access it.
The document.write only be passed after timeago() therefore does not exist over the <div>, so just call "timerago" after using document.write Try:
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
document.write("<div id='na'> aaaaa </div>");
timeago('1376743609');
</script>