i am trying to validate if a certain company was already picked for an application. the companyList format is:
60,261,420 ( a list of companyID)
I used
cID = $('#coName').val().split('::')[1];
to get the id only.
I am calling this function by passing say 60:
findCompany = function(value) {
var v = /^.+60,261,420$/.test(value);
alert(v);
}
when I pass the exact same string, i get false. any help?
Well if your company list is a list of numeric IDs like that, you need to make the resulting regular expression actually be the correct expression — if that's even the way you want to do it.
Another option is to just make an array, and then test for the value being in the array.
As a regex, though, what you could do is this:
var companyList = [<cfoutput> whatever </cfoutput>]; // get company ID list as an array of numbers
var companyRegex = new RegExp("^(?:" + companyList.join('|') + ")$");
Then you can say:
function findCompany(id) {
if (companyRegex.test(id)) alert(id + " is already in the list!");
}
Why not split the string into an array, like you did for your testing, iterate over the list and check if it's in?
A regexp just for that is balls, overhead and slower. A lot.
Anyway, for your specific question:
You’re checking the string "60" for /^.+60,261,420$/.
.+60 will obviously not match because you require at least one character before the 60. The commas also evaluate and are not in your String.
I don’t quite get where your regexp comes from.
Were you looking for a regexp to OR them a hard-coded list of IDs?
Code for splitting it and checking the array of IDs:
findCompany = function(value) {
$('#coName').val().split('::').each(function(val){
if(val == value) return true;
});
return false;
}
Related
I have this string made up for a TMS program... I later found out I want the program to NOT select these postalcodes, it's now matching the string. I want it to be able to select anything between 1000-10000\s*a-zA-Z except for this:
(8388|8389|8390|8391|8392|8393|8394|8395|8396|8397|8398|8400|8401|8403|8404|8405|8406|8407|8408|8409|8410|8411|8412|8413|8414|8415|8420|8421|8422|8423|8424|8425|8426|8427|8428|8430|8431|8432|8433|8434|8435|8440|8441|8442|8443|8444|8445|8446|8447|8448|8449|8451|8452|8453|8454|8455|8456|8457|8458|8459|8461|8462|8463|8464|8465|8466|8467|8468|8469|8470|8471|8472|8474|8475|8476|8477|8478|8479|8481|8482|8483|8484|8485|8486|8487|8488|8489|8490|8491|8493|8494|8495|8497|8500|8501|8502|8503|8505|8506|8507|8508|8511|8512|8513|8514|8515|8516|8517|8520|8521|8522|8523|8524|8525|8526|8527|8528|8529|8530|8531|8532|8534|8535|8536|8537|8538|8539|8541|8542|8550|8551|8552|8553|8554|8556|8560|8561|8563|8564|8565|8566|8567|8571|8572|8573|8574|8581|8582|8583|8584|8600|8601|8602|8603|8604|8605|8606|8607|8608|8611|8612|8613|8614|8615|8616|8617|8618|8620|8621|8622|8623|8624|8625|8626|8627|8628|8629|8631|8632|8633|8635|8636|8637|8641|8642|8644|8647|8650|8651|8658|8700|8701|8702|8710|8711|8713|8715|8721|8722|8723|8724|8730|8731|8732|8733|8734|8735|8736|8737|8741|8742|8743|8744|8745|8746|8747|8748|8749|8751|8752|8753|8754|8755|8756|8757|8758|8759|8761|8762|8763|8764|8765|8766|8771|8772|8773|8774|8775|8800|8801|8802|8804|8805|8806|8807|8808|8809|8811|8812|8813|8814|8816|8821|8822|8823|8830|8831|8832|8833|8834|8835|8841|8842|8843|8844|8845|8850|8851|8852|8853|8854|8855|8856|8857|8860|8861|8862|8871|8872|8880|8881|8882|8883|8884|8885|8890|8891|8892|8893|8894|8895|8896|8897|8899|8900|8901|8902|8903|8911|8912|8913|8914|8915|8916|8917|8918|8919|8921|8922|8923|8924|8925|8926|8927|8931|8932|8933|8934|8935|8936|8937|8938|8939|8941|9001|9003|9004|9005|9006|9007|9008|9009|9011|9012|9013|9014|9021|9022|9023|9024|9025|9026|9027|9031|9032|9033|9034|9035|9036|9037|9038|9040|9041|9043|9044|9045|9047|9050|9051|9053|9054|9055|9056|9057|9060|9061|9062|9063|9064|9067|9071|9072|9073|9074|9075|9076|9077|9078|9079|9081|9082|9083|9084|9086|9087|9088|9089|9091|9100|9101|9102|9103|9104|9105|9106|9107|9108|9109|9111|9112|9113|9114|9121|9122|9123|9124|9125|9131|9132|9133|9134|9135|9136|9137|9138|9141|9142|91439144|9145|9146|9147|9148|9150|9151|9152|9153|9154|9155|9156|9160|9161|9162|9163|9164|9166|9171|9172|9173|9174|9175|9176|9177|9178|9200|9201|9202|9203|9204|9205|9206|9207|9211|9212|9213|9214|9215|9216|9217|9218|9219|9221|9222|9223|9230|9231|9233|9240|9241|9243|9244|9245|9246|9247|9248|9249|9250|9251|9254|9255|9256|9257|9258|9260|9261|9262|9263|9264|9265|9269|9270|9271|9280|9281|9283|9284|9285|9286|9287|9288|9289|9290|9291|9292|9293|9294|9295|9296|9297|9298|9299|9851|9852|9853|9871|9872|9873|9950)\s*[a-zA-Z]{2}
I obviously tried the [^] function and the ?: function but I can't get it working properly.
Just break this string into a set(I think slice function can do that) then sort it and every time you get a value match if it exists in this set or not.
Lets make it easier, I am guessing you are getting numbers in string format of some sort with some form of separation in this case "|".
Step one create array by splinting string based on separator
Step two use filter function that will return a new array based on conditions you provide as shown in example.
Below example takes into consideration edge cases e.g. we are only comparing numbers alphabets are of lesser comparative value to us. What we have to make sure is any comparative value starts with number rest is is all gibberish. So extract number and run bit of magic on that.
Your sting was too long I have used a hypothetical scenario to give you what you want. Rest should be self explanatory in example.
data = '100|999|1000|s1000|10d00|1000f|2500|7500|10000|10001|10500';
dataArray = data.split("|");
dataFiltered = dataArray.filter(function (item) {
extractedNumber = item.match(/^\d+/g);
if(extractedNumber > 999 && extractedNumber <10001) {
return item;
}})
console.log(dataFiltered)
to check on whats being extracted run following and update function as needed.
data = '100|999|1000|s1000|10d00|1000f|2500|7500|10000|10001|10500';
dataArray = data.split("|");
dataFiltered = dataArray.filter(function (item) {
extractedNumber = item.match(/^\d+/);
console.log(extractedNumber);
if(extractedNumber > 999 && extractedNumber <10001) {
return item;
}})
console.log(dataFiltered)
I need to construct and populate a json object with values coming from a method.
A bit of background to this: I'm searching pdf documents with a designated keyword and if I find any match, for each match I need to save:
-the whole sentence where the match is found
-the search term (defined elsewhere: the search term is always the same, so it's really redundant here, but I might need it in the json object that's why I'm including it)
-the result (which is the index where the search term is found in a whole sentence and it should be an integer)
So, here is some code.
I have this function call inside a loop (the loops goes through the pages and then there is a second loop that goes through the text):
for(var i = 0; i < items.length; i++){
lineWithResult = searchPdf(block.str);
if(lineWithResult != null){
console.log(lineWithResult + " wordCounter is " + wordCounter);
}
}
and the function itself:
function searchPdf(toSearch){
var result = toSearch.toLowerCase().indexOf(searchTerm);
if(result >=0){//if match is found
wordCounter++;
//console.log("toSearch " + toSearch + " result is " + result + " wordCounter " + wordCounter);
return toSearch;
}
else{//if match not found
return null;
}
}
SO I need to construct a json object that at each iteration takes in the parameters discussed above:
So, what would be the best way - I'm a bit rusty with json?
I think I would start by creating an empty object like so (if that's even a valid definition):
var searchResult = {"Line" : "", "SearchTerm" : "", "Result" : ""}
If the above is right, where do I define the object and how do I fill it up with the relevant values? Bear in mind that there will be a lot of Lines, one search term and a lot of Results because the documents (a pdf) which I will use are quite big and can returns lots of matches
thanks
With saying something like that:
var searchResult = {"Line" : "", "SearchTerm" : "", "Result" : ""}
You have already defined the object. JavaScript (at this point) is prototypical, not a "class" based language. JSON in JavaScript is not much more than just a plain JavaScript object. If you want to to create multiple objects of that kind, you have various options. I recommend you to read about JS Object creational patterns.
Here is a good link.
That being said, you could do something like that:
// ... maybe inside a function
return {
line: myLineValue,
searchTerm: mySearchtermValue,
result: myResult
}
There is no need to init something with empty values; you just create the object with the curly brackets.
Hope this makes sense to you; if not, let me know in the comments, and I will try to improve my answer. :-)
I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});
I make a serialized list (with JQuery) and then want to delete a Parameter/Value pair from the list. What's the best way to do this? My code seems kinda clunky to take care of edge conditions that the Parameter/Value pair might be first, last, or in the middle of the list.
function serializeDeleteItem(strSerialize, strParamName)
{
// Delete Parameter/Value pair from Serialized list
var strRegEx;
var rExp;
strRegEx = "((^[?&]?" + strParamName + "\=[^\&]*[&]?))|([&]" + strParamName + "\=[^\&]*)|(" + strParamName + "\=[^\&]*[&])";
rExp = new RegExp(strRegEx, "i");
strSerialize = strSerialize.replace(rExp, "");
return strSerialize;
}
Examples / Test rig at http://jsfiddle.net/7Awzw/
EDIT: Modified the test rig to preserve any leading "?" or "&" so that function could be used with URL Query String or fragment of serialized string
See: http://jsfiddle.net/7Awzw/5/
This version is longer than yours, but imho it's more maintainable. It will find and remove the serialized parameter regardless of where it is in the list.
Notes:
To avoid problems with removing items in the middle of an array, we iterate in reverse.
For exact matching of parameter names, we expect them to start at the beginning of the split string, and to terminate with =.
Assuming there is just one instance of the given param, we break once it's found. If there may be more, just remove that line.
Code
function serializeDeleteItem(strSerialize, strParamName)
{
var arrSerialize = strSerialize.split("&");
var i = arrSerialize.length;
while (i--) {
if (arrSerialize[i].indexOf(strParamName+"=") == 0) {
arrSerialize.splice(i,1);
break; // Found the one and only, we're outta here.
}
}
return arrSerialize.join("&");
}
This fails a few of your tests - the ones with serialized strings starting with '?' or '&'. If you feel those are valid, then you could do this at the start of the function, and all tests will pass:
if (strSerialize.length && (strSerialize[0] == '?' || strSerialize[0] == '&'))
strSerialize = strSerialize.slice(1);
Performance Comparison
I've put together a test in jsperf to compare the regex approach with this string method. It's reporting that the regex solution is 49% slower than strings, in IE10 on 32-bit Win7.
I have a string that is JSON values separated by /r. It's sort of like records in a DB table. It looks like:
"{"id":"id","hole":"hole","stat":"stat","value":"value"}/r{"id":1354075540949,"hole":"1","stat":"score","value":"4"}/r{"id":1354075540949,"hole":"1","stat":"putts","value":"1"}/r{"id":1354075540949,"hole":"1","stat":"fir","value":"y"}/r{"id":1354075540949,"hole":"1","stat":"gir","value":"n"}/r"
The first row is the column names (id, hole, stat, value) and I just give them the same value. All other rows separated by /r is the actual data.
I split this string by /r, then loop through the result and push the result of JSON.parse() of each element to an array so now I have an array of objects with properties of the given structure (id, hole, stat, value). Everything is working except the 'id' field ends up being true or false instead of the big long number. Why is it doing that?
var tblData = localStorage.getItem(tblName).split("/r");
var data = new Array();
// fill the array
for (i = 1; i < tblData.length - 1; i++)
data.push(JSON.parse(tblData[i]));
[EDIT]
Seems this does work, but there is a jQuery.grep() I run right after this that's setting the id properties to true/false.
var changeRecords = jQuery.grep(data, func);
Where func is:
function (v) { return v.id == gCurrentRoundID && v.hole == gCurrentHole; }
Not sure why it would be setting id to true/false though.
[EDIT2]
Nevermind, I found my error. The function above wasn't the right one and the one I did have only had 1 equal sign for v.id = gCurrentRoundID, which is why it was setting it to true/false.
I would just manually change the whole string to valid JSON. Have it start with a [ and end with a ], then replace all those /rs with commas. The end result should look like
"[{"id":"id","hole":"hole","stat":"stat","value":"value"},{"id":1354075540949,"hole":"1","stat":"score","value":"4"},{"id":1354075540949,"hole":"1","stat":"putts","value":"1"},{"id":1354075540949,"hole":"1","stat":"fir","value":"y"},{"id":1354075540949,"hole":"1","stat":"gir","value":"n"},]"
Then parse that through JSON.parse
Just note that that last trailing comma may cause problems in IE8. If so, you should be able to manually fix that fairly easily. Something like s = s.substr(0, s.length - 2) + ']';