Javascript need variable that can represent any number - javascript

I'm a javascript novice so this may be a dumb question. I'm trying to generate a script that takes the phrase "(x items)" and changes it to "(x)", where x can represent any number.
Here's what I have now:
<script type="text/javascript">
$(document).ready(function(){
function changeText(){
$(".CartLink:contains('2 items')").html('Cart <span>(2)</span>');
}
changeText();
$(document).ajaxSuccess(function() {
changeText();
});
});
</script>
The above script is able to replace the phrase "(2 items)" with "(2)" but I need to modify the script so that 2 can be any number. Thank you.
This is the HTML that .CartLink element contains:
<li style="display:" class="CartLink">Cart <span>%%GLOBAL_CartItems%%</span></li>

Ideally this should be a server-side task. But if you have a limitation requiring you to do this client-side...
You don't need to replace all of the html. You can simply modify the text of the span:
$('.CartLink span').text(function(_, val) {
return val.replace(' items', '');
});

Your can use split to seperate the count and text.
http://jsfiddle.net/B2meD/
$( document ).ready(function() {
$(".CartLink").html('Cart <span>'+$(".CartLink").text().split(" ")[0]+'</span>');
});

Javascript as a string replace method. So you can simply remove the items part.
var foo = ('2 items');
var newFoo = foo.replace("items", "");
Then newFoo would become ('2')

S('.CartLink').text($('.CartLink').text().split(' ')[0])

Where are you getting the "2" variable from?
var items = 2;
items ++; //items = 3;
$('.Cart').html("Items in cart:" + items.toString() + ". Foo");
See how I added the "+" to add up the strings?
I must add, this is just bad js.
For making your items variable:
var str = "(Items 2)";
var numberStr = "(" + str.split(" ").pop(); //makes "(2)" or use .replace or whatever works.
Keep in mind that making a variable from a string will result in another string. If you want to manipulate your new items var as a number, you have to get an integer like so,
var numberStr = "(3)";
var int = parseFloat(numberStr.replace(/["'()]/g,""));

If you replace your changeText function with this it should work as you want:
function changeText() {
var itemCountSpan = $(".CartLink a span")
if (/(\d+) items/.test(itemCountSpan.text())) {
itemCountSpan.text(RegExp.$1);
}
}

Here's a simple RegEx version.
$(document).ready(function(){
function changeText(){
$(".CartLink").each(function() {
var newhtml = $(this).html().replace(/\((\d+) items\)/, "($1)");
$(this).html(newhtml);
});
}
changeText();
});
It looks at every element with the CartLink class for the string (x items) where x is one or more digits and removes the word "items". $1 is a property that gets set when the (\d+) parenthesised match is made, allowing us to use the number we want in our replacement string.

Related

Get HTML element attribute from javascript

I stuck again in beginner-spheres of JS. :/
I want to get the number from data-channel-id, which is found by the call in variable spans:
<main class="soft--top" data-channel-id="348" data-preview-mode="">
This is my JS:
window.onload = function (){
var spans = document.getElementsByTagName('main')[0];
var res = /[0-9]+/;
var match = res.exec(spans);
console.log(match);
}
I don't know how to proceed.
The Regex is correct, the document. variable "spans" shows the correct result, but matching won't show any output in the console.
What am I missing?
spans in your code currently contains the whole element.
To use only the data-channel-id value, see the code below:
var spans = document.getElementsByTagName('main')[0].getAttribute('data-channel-id');
spans is not string but HTMLElement, to get value of data-channel-id you can use getAttribute as mentioned in comment above or if you really want to use regex convert it to string with .outerHTML
window.onload = function() {
var spans = document.getElementsByTagName('main')[0];
var res = /[0-9]+/;
var match = res.exec(spans.outerHTML);
console.log(match);
}
I want to get the number from "data-channel-id"
No need to use regex. Just:
var spans = document.getElementsByTagName('main')[0];
var match = spans.getAttribute('data-channel-id');
console.log(match);
Working demo here.

Using Javascript to add a span around a decimal value

var value = 2.00
How can I add a span tag around the '.00', so that on my page I would end up with:
2<span>.00</span>
Please note that the '00' can be a different value. Depends on the data being injected.
You can use String#replace
var value = '2.00';
console.log(
value.replace(/\.(\d+)/, '.<sapn>$1</span>')
);
If variable holds a Number then convert it to 2 decimal format string using Number#toFixed and do the same.
var value = 2.00;
console.log(
value.toFixed(2).replace(/\.(\d+)/, '.<sapn>$1</span>')
);
Refer : Specifying a string as a parameter in replace method.
split it into the two parts and add a span to the second part.not sure if you want the decimal place inside the span or not, but this will do it.
var value = '2.00';
var valueParts=value.split(".");
var newValue=valueParts[0] +"<span>."+valueParts[1]+ "</span>";
alert(newValue);
Use the toFixed function
var num = 5.56789;
var n = num.toFixed(2);
if you need back the string to number you can use parseFloat function
var num = parseFloat(n)
You are specifically asking for a "span tag", so here is a JQuery approach:
$(document).ready(function () {
var value = 2.00
value = value.toFixed(2);
$('body').append(value.split('.')[0] + '<span>.' + value.split('.')[1] + '</span>');
});
See this jsfiddle example: https://jsfiddle.net/fictus/tj7df8qh/

.split() a data attribute isn't working when it should

I want to .split(" ") a data attribute value but it returns empty:
var bulletcontent = jQuery(this).closest("div").find("p").attr('data-bcontent');
// split content into words
var words = jQuery(bulletcontent).text().split(" ");
Why isn't this working?
Here is a jsFiddle.
See the fiddle: https://jsfiddle.net/43439o8o/2/
You dont need to get the .text(), the .attr() already return his content:
var bulletcontent = jQuery(content).attr('data-bcontent');
// split content into words
var words = bulletcontent.split(" "); //Remove the .text() method
As you can see at the .attr() method docs, you can use it to return or set the attribute value:
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
change this line:
var words = bulletcontent.split(" ");
$(document).ready(function() {
$(document).on("click", ".click", function() {
// find the bullet content stored in p tag inside li
var content = $(this).prev("p").attr('data-bcontent');//get the p attr
alert(content)
var words = content.split(' ')//split
alert(words[0]);//alert first value
alert(words[1]);//alert second value
});
});
DEMO
You can use directly function split() on the string:
var words = bulletcontent.split(" ");
for example you can see this link
.split() is a Method of String in Javascipt so there's no need to use jQuery. just add .split(' ') right next to your variable(String).
.split() returns array of strings depends on how you want to plit the original string.
This should work for you.
var words = bulletcontent.split(" ");
You can use this:
var words = bulletcontent.split(" ");

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

Categories