onchange method not showing text after using substring javascript - javascript

Somehow there is a problem when I use the substring in javascript. I'm trying to take the last 2 letters out of a 4 letter value and print in out in the div with id=text.
This works without using substring
$("#departureroute").change(function () {
var value = (this.value);
$("#test").text(value);
}).change();
This does not work, using substring
$("#departureroute").change(function () {
var value = (this.value);
var res = value.substring(2, 2);
$("#test").text(res);
}).change();
Any ideer what is happening?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
Per the manual, the substring method takes the index of the beginning of the substring and index of the end of the substring. The second argument is optional and will go to the end of the string if not provided. So change it to:
$("#departureroute").change(function () {
var value = (this.value);
var res = value.substring(2);
$("#test").text(res);
}).change();

Related

Javascript regex match and get values from string

I've got a string of text which can have specific tags in it.
Example: var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
What I'm trying to do is do a regex match against the <pause #></pause> tag.
For each tags found, in this case it's <pause 4></pause> and <pause 7></pause>. What I want is to grab the value 4 and 7, and the string length divided by for the string in between the <pause #>...</pause> tags.
What I have for now is not much.
But I cant figure out how to grab all the cases, then loop through each one and grab the values I'm looking for.
My function for this looks like this for now, it's not much:
/**
* checkTags(string)
* Just check for tags, and add them
* to the proper arrays for drawing later on
* #return string
*/
function checkTags(string) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)<\/pause>/g
}
var matchedPauses = string.match(regex.pause);
// For each match
// Grab the pause seconds <pause SECONDS>
// Grab the length of the string divided by 2 "string.length/2" between the <pause></pause> tags
// Push the values to "pauses" [seconds, string.length/2]
// Remove the tags from the original string variable
return string;
}
If anyone can explain my how I could do this I would be very thankful! :)
match(/.../g) doesn't save subgroups, you're going to need exec or replace to do that. Here's an example of a replace-based helper function to get all matches:
function matchAll(re, str) {
var matches = [];
str.replace(re, function() {
matches.push([...arguments]);
});
return matches;
}
var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
var re = /<pause (\d+)>(.+?)<\/pause>/g;
console.log(matchAll(re, string))
Since you're removing tags anyways, you can also use replace directly.
You need to make a loop to find all matched groups of your RegExp pattern in the text.
The matched group is an array containing the original text, the matched value and the match text.
var str = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
function checkTags(str) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)\<\/pause>/g
}
var matches = [];
while(matchedPauses = regex.pause.exec(str)) {
matches.push([matchedPauses[1], matchedPauses[2].length /2]);
};
return matches;
}
console.log(checkTags(str));
As a start point since you have not much so far you could try this one
/<pause [0-9]+>.*<\/pause>/g
Than to get the number out there you match again using
/[0-9]+>/g
To get rid of the last sign >
str = str.slice(0, -1);

using substring to clear the last letter of a string in javascript

I have a textarea with the id display_main.
I need this backspacing function to clear the last letter or number of the text area.
This code below did not work.
Please explain.
function backspacing(){
document.getElementById("display_main").substring(0, display_main.length - 1);
}
document.getElementById returns an element. Elements aren’t strings, so it doesn’t make sense to take substrings of them. You’ll need to use its value property, which is the text contained in the textarea (and many other input elements):
function backspacing() {
var displayMain = document.getElementById("display_main");
displayMain.value.substring(0, displayMain.value.length - 1)
}
Also, substring doesn’t modify the string it’s called on; strings are immutable. It returns a new string, which you need to assign to something:
function backspacing() {
var displayMain = document.getElementById("display_main");
displayMain.value = displayMain.value.substring(0, displayMain.value.length - 1);
}
Because you're trying to substring the element, instead of the element's value
var element = document.getElementById("display_main");
element.value = element.value.substring(0, element.value.length - 1);
Should be:
function backspacing(){
var textarea = document.getElementById("display_main");
textarea.value = textarea.value.substring(0, textarea.value.length - 1);
}
get first text area value and apply substring function.
textAreaValue = document.getElementById("display_main").value
then apply substring function on value then again set modify value to textarea.
You can clear the last character of the textbox and assign it to itself with this code
function backspacing() {
var textbox = document.getElementById("display_main");
textbox.value = textbox.value.slice(0,-1) ;
}
Or if you have jQuery library loaded you can use :
function backspacing() {
$("#display_main").val($("#display_main").val().slice(0,-1));
}

Javascript need variable that can represent any number

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.

Why does this jQuery code not work?

Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

How to get portion of the attribute value using jquery

I have attribute value as:
<div id = "2fComponents-2fPromotion-2f" class = "promotion">
Now I want to get only portion of it, say Promotion and its value 2f, how can I get this using jquery ? Do we have built in function for it ?
You can use a regular expression here:
var attId = $(".promotion").attr("id");
// Perform a match on "Promotion-" followed by 2 characters in the range [0-9a-f]
var match = attId.match(/Promotion-([0-9a-f]{2})/);
alert(match[1]); // match[0] contains "Promotion-2f", match[1] contains "2f"
This assumes that the "value" of Promotion is a hexadecimal value and the characters [a-f] will always be lower case. It's also easily adjusted to match other values, for instance, if I change the regex to /component-([0-9a-f]{2})/, the match array would be ["component-3a", "3a"].
The match method takes a regular expression as its input and searches the string for the results. The result is returned as an array of matches, with the first index being the complete match (equivalent regex for this only would be /Promotion-[0-9a-f]{2}/). Any sub-expression (expressions enclosed in parenthesis) matches are added to the array in the order they appear in the expression, so the (Promotion) part of the expression is added to the array at index 1 and ([0-9a-f]{2}) is added at index 2.
match method on MSDN
var id = $("div.promotion").attr("id");
var index = id.indexOf("Promotion");
var promotion = '';
// if the word 'Promotion' is present
if(index !== -1) {
// extract it up to the end of the string
promotion = id.substring(index);
// split it at the hyphen '-', the second offset is the promotion code
alert(promotion.split('-')[1]);
} else {
alert("promotion code not found");
}
you can get the id attribute like this:
var id= $('div.promotion').attr('id');
But then I think you would have to use regular expressions to parse data from the string, the format doesn't appear to be straight forward.
If you are storing lots of info in the id could you consider using multiple attributes like:
<div class="promotion" zone="3a-2f-2f" home="2f"></div>
Then you could get the data like this:
var zone= $('div.promotion').attr('zone');
var home= $('div.promotion').attr('home');
Or you could use jQuery.data()
HTH
$(function () {
var promotion = $('.promotion').attr('id').match(/Promotion-([0-9a-f]{2})/);
if (promotion.length > 0) {
alert(promotion[1]);
}
else {
return false;
}
});

Categories