I send a string from a server to the Firefox Browser in the format below:
"KEY:a1 VAL:123.45"
And this string can contain many such records.
Here is the code I have written:
var e;
var reply = request.responseText;
var txt = "", tab, key = "", val = "";
var x = reply.getElementsByTagName("KEY:");
for(i = 0; i < x.length; i++)
{
txt = x[i].childNodes[0].nodeValue; // "KEY:%c%c VAL:%.2F"
tab = txt.split(":");
key = "table_" + tab[1].substring(0,1);
val = tab[2];
e = document.getElementById(key);
e.innerHTML = val;
e.style.display = "block";
}
val displays "KEY:a1 VAL:123.45" instead of the expected "123.45" (and of course the key variable is also wrong, not matching a table cell, just picking the first one in the table).
I don't even know how to display the key and val values (document.write() and alert() do nothing and I don't see how to trace this code in Firefox).
Any idea, tip, correction, or code example is welcome but please don't recommend using any library, I want to do it with little code.
EDIT: from the two comments, I understand that there are two distinct ways to proceed: either using DOM objects and HTML tags, or using 'strings'. I would prefer to keep using the format above, so please guide me to a 'string' solution. Thanks!
You can use a simple regular expression to extract the information from the string:
var value = "KEY:a1 VAL:123.45",
pattern = /KEY:(\S+) VAL:(.+)$/g;
var result = pattern.exec(value);
// result[1] == 'a1'
// result[2] == '123.45'
In your case, you'd use request.responseText instead of value.
Related
I am having some issues using string interpolation in a regex, however I have also tried to log it to the console and I can see that I am doing it incorrectly.
I am trying to loop through an array of weather types to see if my API request returned a type of weather which requires me to add a class to one of my elements in the UI.
I iniitally thought the issue was using array[x] in the regex, but I have assigned this to a variable p and am still getting the same result.
let weatherTypes = ['rain', 'clouds', 'snow', 'clear', 'thunderstorm'];
for (var x= 0; x <= weatherTypes.length; x++) {
let p = weatherTypes[x];
console.log(p)
var searchPattern = `/${p}/i`;
var result = this.state.description.match(searchPattern);
console.log(`splash--weather-${p}`);
if(result !== null) {
var element = document.getElementById("splashContact");
element.classList.add(`splash--weather-${weatherTypes[0]}` );
}
}
The logic to add the class works when I abstract it out of the for loop so I know that part is working fine.
Can somebody please point me in the right direction?
edit Have now used backticks instead of quotation marks
searchPattern is a string so you just need to use the RegExp constructor before using it.
var searchPattern = `${p}/i`;
var searchPatternRegex = RegExp(`${searchPattern}`);
I have a search form that allows the user to add as many search terms as they like. When the user enters all of the search terms and their search values and clicks search, a text box will be updated with the search terms. I've got this working with a for loop, but I'm trying to improve my dev skills and am looking for a way to do this with map\filter instead.
Here's the code I'm trying to replace:
var searchTerms = $("#search-form").find(".mdc-layout-grid__inner");
var searchString = "";
for(var i = 0; i < searchTerms.length - 1; i ++)
{
var select = $(searchTerms[i]).find(".select2-selection")[0];
var selectText = $(select).select2('data')[0].text + ":";
var textBox = $(searchTerms[i]).find(".mdc-text-field__input")[0];
searchString = searchString += selectText.replace(/\./g,"").replace(/ /g,"") + textBox.value;
if(i < searchTerms.length - 1)
{
searchString = searchString += " ";
}
}
$("#er-search-input").val(searchString);
Here's a codepen of the current solution.
i'm trying the below, but I get the feeling I'm miles away:
const ret = searchTerms.map((u,i) => [
$($(u[i]).find(".select2-selection")[0]).select2('data')[0].text + ":",
$(u[i]).find(".mdc-text-field__input")[0].value,
]);
My question is, is it possible to do this with map?
Firstly you're repeatedly creating a jQuery object, accessing it by index to get an Element object only to then create another jQuery object from that. Instead of doing this, you can use eq() to get a specific element in a jQuery object by its index.
However if you use map() to loop through the jQuery object then you can avoid that entirely by using this to reference the current element in the iteration. From there you can access the required elements. The use of map() also builds the array for you, so all you need to do is join() the results together to build the required string output.
Finally, note that you can combine the regex expressions in the replace() call by using the | operator, and also \s is more robust than using a whitespace character. Try this:
var $searchTerms = $("#search-form").find(".mdc-layout-grid__inner");
var searchString = $searchTerms.map(function() {
var $searchTerm = $(this);
var selectText = $searchTerm.find('.select2-selection').select2('data')[0].text + ':';
var $textBox = $searchTerm.find('.mdc-text-field__input:first');
return selectText.replace(/\.|\s/g, "") + $textBox.val();
}).get().join(' ');
$("#er-search-input").val(searchString);
This doesn't work but I can't see why it wouldn't? any help people? :)
params = qs.split("=", 2),
id = params[1];
if(id.indexOf("?") != -1){
id = id.split("?", 1);
}
basically I want to change the value of 'ID' if the IF statement is true, if not.. it skips it and the value Id remains the default.
Thanks
The result of id = id.split("?", 1) is an array (of at most 1 item), but I think you want id to be a string. That would explain why id is not a string like you want.
I agree with the other comments. Please show us the URL string you want to parse and tell us which piece you're trying to get. Usually, you look for ? first, separate after that and then divide up various key=value sections.
If you had a URL like this:
http://www.example.com?foo=bar
Here's a simple function that gets you all the query parameters into an object:
function getParms(url) {
var sections, key, pieces = url.split("?");
var results = {};
if (pieces.length > 1) {
sections = pieces[1].split("&");
for (var i = 0; i < sections.length; i++) {
key = sections[i].split("=");
results[key[0]] = key[1];
}
}
return(results);
}
Working demo: http://jsfiddle.net/jfriend00/kNG3u/
This may have been asked in the past but I couldnt find a suitable answer. What I am looking for is a method to extract parameters from an sql query such as below. The queries will always be an EXEC statement followed by the query name, and possible parameters.
Here is an example of what I may recieve
EXEC [dbo].[myProcedure] #Param1
This could also be as follows
EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3
Those are the only types of queries that the input will take. As for why I am doing this, well thats another question all together, and I am pretty set on going down this route.
What I am looking for is to be able to take the above strings and produce an array of values such as
['#Param1','#Param2','#Param3',....]
I originally tried to just parese using a simple while statement but I seem to have huge issues there.
I hope this question makes sense,
Cheers,
Nico
[Edit]
Sorted this by using the following statement
function eParams(e) {
var i = e.indexOf('#');
if (i <= 0)
return;
e = e.substring(i);
var p = e.split(',');
var eList = [];
var s = '';
for (var i = 0, j = p.length - 1; i <= j; i++) {
var sP = p[i].trim();
if (sP.indexOf('#') < 0)
continue;
eList.push(sP);
}
}
var str = 'EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3';
(str).match(/(#[^\s,]+)/g);
will return an array.
var s = "EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3";
var i = s.indexOf('#');
var a = s.substr(i).split(/\s*,\s*/);
(error checking omitted)
Im trying to define variable values from values inputted into an input textfield onkeyup. I've never done this before and cant find it on Google so was wondering if anybody had any idea on how to do this...
<input type="text" id="values" />
var numberone = "";
var numbertwo = "";
var numberthree = "";
Imagine the user types into the input box "thomas the tankengine" thomas would become 'var numberone'. 'the' would become number two and so on...
Is this possible?
You can split a string by spaces using the split() function
eg
var words = document.getElementById("values").value.split(' ');
var op1 = words[0];
...
Possible, but unwise and would require messing about with eval if you didn't want the variables to end up in the global scope.
Any time you variable variables can solve a problem, it can be better solved by using an array (for sequential data) or object (for named data).
This is exactly the sort of job that arrays are designed to handle.
var numbers = document.getElementById('values').value.split(' ');
console.log(numbers[0]);
console.log(numbers[1]);
console.log(numbers[2]);
How about saving each word in an index of an array so you can have a dynamic number of words:
var max_words = 3;
$('#values').on('keydown', function (event) {
if (event.keyCode == 32) {//32 == space key
var arr = $(this).val().split(' '),
len = max_words < arr.length ? max_words : arr.length,
out = [];
for (var i = 0; i < len; i++) {
out.push(arr[i]);
}
}
});
Here is a jsfiddle to demonstrate this code: http://jsfiddle.net/r8dXw/1/ (Note that the output is logged via console.log so check your console to see the output)