Javascript to strip html and currency symbol - javascript

I have this html:
<span class="price-amount amount"><span class="price-currencySymbol">£</span>49.99</span>
I want to extract just the value of '49.99' without the html and currency symbol.
I have tried this:
function() {
var element = document.querySelector('.price-amount');
var price = element.innerHTML.replace('£', '');
return price;
}
But the result is this:
<span class="price-currencySymbol">£</span>49.99
Rather than: 49.99

Try this
var price = element.innerHTML.match(/\d+\.\d+/)[0];
where
.match searches the pattern of price using regex.
[0] returns the first match, and in your case it would be the only match.

If you want to delete what's in the '.price-currencySymbol' span in every case, you juste have to empty its html:
document.querySelector(".price-amount").innerHTML = "";

By using selector logic and accessing the proper text node you don't even need to use regexp.
var price = document.querySelector(".price-amount")
.childNodes[1].textContent;
console.log(`Extracted price: ${price}`);
<span class="price-amount amount"><span class="price-currencySymbol">£</span>49.99</span>

Related

Extract multiple specific characters from string javascript

I have the following innerHTML in element id "word":
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span
I would like to create a function (wordReverter) that removes all of the tags, leaving in the above example, only the word "hello".
Any help would be greatly appreciated, thank you!
function wordReverter() {
var word = document.getElementById("word").innerHTML;
//var rejoinedWord = rejoined word with <span> tags removed
document.getElementById("word").innerHTML = rejoinedWord;
}
Get the innerText and use it as a new innerHtml like below
(function wordReverter() {
var word = document.getElementById("word").innerText;
document.getElementById("word").innerHTML = word;
})()
<div id="word">
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>
</div>
If you have the containing element, you can target it and retrieve it's textContent, otherwise, you can select all the elements of interest and retrieve their content as below:
function wordReverter() {
let letters = document.querySelectorAll('.white,.green')
return Array.from(letters).map(l=>l.textContent).join('')
}
console.log(wordReverter())
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>

Using javascript/jquery to remove text after a certain character

Is there a way to replace/remove the text only after a certain character using jQuery or Javascript? I want to remove text after the dot '.' from an element.
You can easily do it with .split() like this:
var text = 'daslkdaskldj.asdasdasd';
text.split('.')[0];
here is fiddle
var string = "Test String.Test String 2".split('.')[0];
console.log(string)
Will give you the output:
Test String
Here is a working example:
https://jsfiddle.net/zr2wg90d/
Your question is a bit unclear. But to remove all text after the first '.'(dot) This can do the trick with an input field. There are a lot of ways to achieve this. This is a solution without jQuery.
function removeAfterDot() {
var test = document.getElementById("myInput").value;
alert("String before remove: " + test);
test = test.substr(0, test.indexOf('.'));
alert("String after remove: " + test);
}
<input type="text" id="myInput" onchange=removeAfterDot();>
text.substr(0, text.indexOf('.'));
Hope this helps.
var q = 'https://stackoverflow.com/questions/';
q = q.substring(0, q.indexOf('.'));
alert(q);
Try this
var yourString = "Hello. World";
yourString.substr(0, yourString.indexOf('.'));
Will give you the following output
Hello
you can use this. split any string at the character you give it.
<p>first part . second part</p>
remove
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('a').click(function(){
var the_string = $('p').text();
var removed = the_string.split('.', 1);
$('p').text(removed);
});
</script>
for me splice works, I basically use this for removing characters after a hyphen or a comma etc.
var text = 'Tellme.more';
text.split('.')[0]);
//Consoles out -> Tellme

RegExp. Get only text content of tag (without inner tags)

I have string with html code.
<h2 class="some-class">
<a href="#link" class="link" id="first-link"
<span class="bold">link</span>
</a>
NEED TO GET THIS
</h2>
I need to get only text content of h2.
I create this regular expression:
(?<=>)(.*)(?=<\/h2>)
But it's useful if h2 has no inner tags. Otherwise I get this:
<a href="#link" class="link" id="first-link"
<span class="bold">link</span>
</a>
NEED TO GET THIS
Never use regex to parse HTML, check these famous answers:
Using regular expressions to parse HTML: why not?
RegEx match open tags except XHTML self-contained tags
Instead, generate a temp element with the text as HTML and get content by filtering out text nodes.
var str = `<h2 class="some-class">
<a href="#link" class="link" id="first-link"
<span class="bold">link</span>
</a>
NEED TO GET THIS
</h2>`;
// generate a temporary DOM element
var temp = document.createElement('div');
// set content
temp.innerHTML = str;
// get the h2 element
var h2 = temp.querySelector('h2');
console.log(
// get all child nodes and convert into array
// for older browser use [].slice.call(h2...)
Array.from(h2.childNodes)
// iterate over elements
.map(function(e) {
// if text node then return the content, else return
// empty string
return e.nodeType === 3 ? e.textContent.trim() : '';
})
// join the string array
.join('')
// you can use reduce method instead of map
// .reduce(function(s, e) { return s + (e.nodeType === 3 ? e.textContent.trim() : ''); }, '')
)
Reference :
Fastest way to convert JavaScript NodeList to Array?
Rgex is not good for parsing HTML, but if your html is not valid or any way you like to use regex:
(?!>)([^><]+)(?=<\/h2>)
try Demo
It's getting last texts before closing tag of </h2> (IF EXISTS)
To avoid null results changed * to +.
This Regex is completely limit and fitting to limited situations as question mentioned.
demo
var h2 = document.querySelector('h2')
var h2_clone = h2.cloneNode(true)
for (let el of h2_clone.children) {
el.remove()
}
alert(h2_clone.innerText)

Get text between tags using javascript

I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.

How to add html element to the current textarea value, and output it as raw html

I need to style the total cost for user added in a textarea.
I have this fragment of code:
$("#student_teacher_profile_for_teaching_amount").keyup(function(e) {
var new_str, price, regex, str;
regex = /[0-9]+\.[0-9]{1,2}|[0-9]/;
str = $(this).val();
console.log(str);
price = str.match(regex);
if(price) {
if( $("#to_teach_ammount").length > 0 ) {
$("#to_teach_ammount").html(price[0]);
} else {
new_str = str.replace(regex, "<span id='to_teach_ammount'>" + price[0] + "</span>");
$(this).val(new_str);
}
$("#to_teach_total").val(price[0]); #this is and hiddent input filed
}
});
As a result of it I get:
some text before numbers <span id='to_teach_ammount'>2</span>
in my textarea.
How can I convert this into raw HTML?
This is not possible with a common <textarea> element, which only accepts plain text. You will have to use a (rich-text)-plugin, for example with jQuery. Have a look here: http://www.strangeplanet.fr/work/jquery-highlighttextarea/
The to_teach_total should not be a textarea. Instead it should be an element which expects html
Then use $(this).html(new_str) to set html
This html() method can also be passed a function which can take old html as parameter and return a new string to be set as new html

Categories