Javascript Regular expression test method no working properly [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why RegExp with global flag in Javascript give wrong results?
I have the following method to which I'm passing these parameters:
var stringValue = "50, abc";
var stringArray = stringValue.split(",");
var agePattern = /^([0-9]|[1-9][0-9]|[1][0-4][0-9]|[1][5][0])$/g;
age = getMatchingString(stringArray, agePattern);
//---------------------------------------------
function getMatchingString(stringArray, regexPattern) {
//alert("getMatchingString");
for (var i=0; i < stringArray.length; i++) {
if (regexPattern.test(stringArray[i])) {
return (stringArray[i].match(regexPattern)).toString();
}
}
return null;
}
Chrome shows the following funny behavior where test method with stringArray[i] and stringArray[0] show different values even when i = 0 as shown in the image:
Can someone explain this to me please?

var stringValue = "50, abc";
var stringArray = stringValue.split(",");
var age = getMatchingString(stringArray);
function getMatchingString(stringArray)
{
var len=stringArray.length;
for (var i=0; i < len; i++)
{
if(!isNaN(stringArray[i]))
{
return stringArray[i]
}
}
return null;
}
alert(age)//50
Perhaps, if you are looping through the array to check for the existence of a numeric value as such age, isNaN is much better a option to use here than using a regex pattern.
DEMO

Related

How to shorten conditional statements in Javascript [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 6 years ago.
I have a very long conditional statement like the following:
How to shorten condition statements in Javascript?
var str = document.getElementsByClassName("label");
for(var i = 0; i<str.length; ++i){
if(str[i].innerHTML === "US" || str[i].innerHTML === "VN"|| str[i].innerHTML === "War"...){
str[i].style.display = "none";}}
Use Includes , includes is supported in es6
var values = ["US","VN","War"];
if (values.includes(str[i].innerHTML)){
}
You can do it with indexOf(..)>-1 :
var values = ["US","VN","War"];
if (values.indexOf(str[i].innerHTML)>-1){
}
You can use array with indexOf or includes.
Note: includes will work on ES6 supported browsers
Working snippet:
var str = document.getElementsByClassName("label");
var options = ['US', 'VN', 'War'];
for(var i = 0; i<str.length; ++i){
var text = str[i].innerHTML;
if(options.indexOf(text) !== -1){
str[i].style.display = "none";
}
}
<span class="label">US</span>
<span class="label">USA</span>
Testing via a regular expression makes it pretty short:
if (/^(US|VN|War|etc)$/.test(str[i].innerHTML)) {
In context:
var str = document.getElementsByClassName("label");
var re = /^(US|VN|War|etc)$/;
for (var i = 0; i < str.length; ++i) {
if (re.test(str[i].innerHTML)) {
str[i].style.display = "none";
}
}
If required you can make it a case-insensitive test by adding the i flag to the regex:
var re = /^(US|VN|War|etc)$/i;
This can be done using jquery by selecting all elements with class label then filtering them by checking that their innerHTML is within the array ['US','VN'] and for all that satisfy the filter condition, we change the css style display
$(".label").filter(function (){
return ['US','VN'].includes(this.innerHTML);
}).css("display","none");

Check that the array is unique [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript: Determine whether an array contains a value
var thelist = new Array();
function addlist(){
thelist.push(documentgetElementById('data').innerHTML);
}
How can I check that the data I push does not already exsist in array thelist?
var thelist = []; // Use the array literal, not the constructor.
function addlist(){
// get the data we want to make sure is unique
var data = documentgetElementById('data').innerHTML;
// make a flag to keep track of whether or not it exists.
var exists = false;
// Loop through the array
for (var i = 0; i < thelist.length; i++) {
// if we found the data in there already, flip the flag
if (thelist[i] === data) {
exists = true;
// stop looping, once we have found something, no reason to loop more.
break;
}
}
// If the data doesn't exist yet, push it on there.
if (!exists) {
thelist.push(data);
}
}
If you don't care about IE < 9 you could also use the Array method "some".
Just have a look at this example:
var thelist = [1, 2, 3];
function addlist(data) {
alreadyExists = thelist.some(function (item) {
return item === data
});
if (!alreadyExists) {
thelist.push(data);
}
}
addlist(1);
addlist(2);
addlist(5);
console.log(thelist);​
http://jsfiddle.net/C7PBf/
Some determines whether at least one element with given constraint (callbacks return value === true) does exist or not.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some
If you are not concerned about IE version 8 or lower, you can use Array.filter:
var thelist = new Array();
function addlist(){
var val = documentgetElementById('data').innerHTML;
var isInArray = theList.filter(function(item){
return item != val
}).length > 0;
if (!isInArray)
thelist.push(val);
}
Or, you could use Array.indexOf:
var thelist = new Array();
function addlist(){
var val = documentgetElementById('data').innerHTML;
var isInArray = theList.indexOf(val) >= 0;
if (!isInArray)
thelist.push(val);
}
Have a look at underscore.js : underscore.js
Then you can check the array as
_.contains(thelist, 'value you want to check');
// The full example
var thelist = new Array();
function addlist(){
var data = documentgetElementById('data').innerHTML;
if(!_.contains(thelist, data)) theList.push(data);
}
or you can add the values to the array without concerning the duplicate values, and after the adding process is finished, you can remove the duplicate elements by
theList = _.uniq(theList);
The second method of course less efficient.

need to create a function that converts a range object that i created myself into a string? [duplicate]

This question already has an answer here:
when i run my code I get the following result []object object] [object object] but should be giving me an ordered array
(1 answer)
Closed 8 years ago.
below is the code that i used to create a range object within my overall programme
function parseRangeString(id, range) {
var myRangeString = range;
var myRangeStringArray = myRangeString.split(/[\s]+/);
var myMax;
var myMin;
var myMinOp;
var myMaxOp;
var myMaxInc = false;
var myMinInc = false;
var op1;
var op2;
var cons1;
var cons2;
op1 = myRangeStringArray[0];
cons1 = parseFloat(myRangeStringArray[1]);
if (myRangeStringArray[2] != null) {
op2 = myRangeStringArray[3];
cons2 = parseFloat(myRangeStringArray[4]);
}
if (cons1 < cons2) {
myMin = cons1;
myMinOp = op1;
myMax = cons2;
myMaxOp = op2;
} else {
myMin = cons2;
myMinOp = op2;
myMax = cons1;
myMaxop = op1;
}
if (myMaxOp.indexOf('=') != -1) {
myMaxInc = true;
}
if (myMinOp.indexOf('=') != -1) {
myMinInc = true;
}
firstRange = new Range(id, myMin, myMax, myMinInc, myMaxInc); //gives back a range object
return firstRange;
}
Now i need to make another function that converts the range object to string, help needed asap because i am stuck atm!
You can overwrite the standard toString function on your javascript objects to make them return whatever you want. Consider this example (demo):
var a = { some_property:'this could be coming from the user' }; // create a new object
a.toString = function(){
// in here, the "this" will point to the object in "a" variable. (well, at least mot of the times)
return this.some_property;
};
console.log(''+a); // force the object to string
If you create a lots of object like this, consider using the prototype of them to place the toString function, will be more efficient, MDN has great examples.
Well i guess i give the same answer every day. :)
JSON.stringify( range );

How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.

How to extract a GET parameter from the URL in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use the get parameter of the url in javascript
Suppose I have this url:
s = 'http://mydomain.com/?q=microsoft&p=next'
In this case, how do I extract "microsoft" from the string?
I know that in python, it would be:
new_s = s[s.find('?q=')+len('?q='):s.find('&',s.find('?q='))]
I use the parseUri library available here:
http://stevenlevithan.com/demo/parseuri/js/
It allows you to do exactly what you are asking for:
var uri = 'http://mydomain.com/?q=microsoft&p=next';
var q = uri.queryKey['q'];
// q = 'microsoft'
(function(){
var url = 'http://mydomain.com/?q=microsoft&p=next'
var s = url.search.substring(1).split('&');
if(!s.length) return;
window.GET = {};
for(var i = 0; i < s.length; i++) {
var parts = s[i].split('=');
GET[unescape(parts[0])] = unescape(parts[1]);
}
}())
Think this will work..

Categories