Simple RegExp question - how to find keys [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Get query string values in JavaScript
Use the get paramater of the url in javascript
I have a long list of URLs where in one part of the URL I've got a command such as 'KEY=123'. I would like to find all those keys.
For Example: /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1
How could this be accomplished? My idea was just to search all the 'KEY' words and look for the number next to it - but I guess there is something much quicker for this.
The language of preference would be Javascript.
EDIT:
The URLs are cluttered and can't be extrapolated out of the text easily. a small example of the text:
2011-07-29 01:17:55.965/somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 685ms 157cpu_ms 87api_cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13`
2011-07-29 01:05:19.566 /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 29ms 23cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13
2011-07-29 01:04:41.231 /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 972ms 78cpu_ms 8api_cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13

The Javascript you'd need would be something like -
var text = 'ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1&key=678';
var matches = text.match(/KEY=\d*|key=\d*/g);
for (i=0; i<matches.length; i++) {
alert(matches[i]);
}
If you wanted just the number, you could do something like -
var text = 'ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1&key=678';
var matches = text.match(/KEY=\d*|key=\d*/g);
for (i=0; i<matches.length; i++) {
alert(matches[i].toLowerCase().replace('key=',''));
}

If you are interested only in the KEY value:
var regex = new RegExp("KEY=(\d+)");
var result = regex.exec(window.location.href);
result would be "123" in your case. If you have multiple lines, then:
var regex = new RegExp("KEY=(\d+)", "gm");
var results = regex.exec(window.location.href);
in this case results is an array.

a = "/somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1";
a.match(/KEY\=(\d+)/gi)

Related

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

Adding space to fill array length

I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);

I would like to get the value of a given token with in a string

I am currently working on a project that will allow me to bring in a string that would have a designated token that I will grab, get the designated value and remove the token and push to an array. I have the following condition which I am using split in JavaScript but it is not splitting on the designated ending token.
This is the beginning string
"~~/Document Heading 1~~<div>This is a test <b>JUDO</b> TKD</div>~~end~~<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>"
Current Code Block
var segmentedStyles = [];
var contentToInsert = selectedContent.toString();
var indexValue = selectedContent.toString().search("~~");
if (indexValue <= 0) {
var insertionStyle = contentToInsert.split("~~");
segmentedStyles.push(insertionStyle);
}
The designated token is enclosed by a "~~ .... ~~". In this code Block it is going through the condition but the string it is not splitting correctly. I am currently getting the Following string pushed to my array.
This is my current result
[,/Document Heading 1<div>This is a test <b>JUDO</b> TKD</div>end,
<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>]
My Goal
I would like to split a string that is coming in if a token is present. For example I would like to split a string starting from ~~.....~~ through ~~end~~. The array should hold two values like the following
segmentedStyles = [<div>This is a test <b>JUDO</b> TKD</div>],[<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>]
You could use a regular expression for matching the parts.
var string = '~~/Document Heading 1~~<div>This is a test <b>JUDO</b> TKD</div>~~end~~<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>',
array = string.split('~~').filter(function (_, i) {
return i && !(i % 2); // just get element 2 and 4 or all other even indices
});
console.log(array);
Assuming the string always starts with ~~/ you could use the following regex to get the array you want
~~([^\/].*)~~end~~(.*)
https://regex101.com/r/hJ0vM4/1
I honestly didn't quite understand what you're trying to accomplish haha, but I sort of understood what you're trying to do :)
First, just trying to make it clear some stuff. If you split() your string using /~~/ as the Regular Expression for splitting you'll get all the bits surrounded by "~~" in an array, like you did.
Second, if you change the tokens to ~~START~~ and ~~END~~ (tokens that never change) you can accomplish what you want by simply doing string.split(/~~(START|END)~~/) - Much shorter and quicker ;)
Third is the string always in the format ~~<something>~~THE STUFF YOU WANT~~end~~MORE STUFF YOU WANT? If it is, I'd suggest doing this:
function splitTheTokens(str) {
var result = [];
var parts = str.split(/~~end~~/);
for (var i = 0; i < parts.length; i++) {
if (!parts[i]) { continue; } // Skips blanks
if (parts[i].indexOf("~~") == 0) {
// In case you want to do something with the name thing:
var thisPartName = parts[i].substring(2, parts[i].indexOf("~~", 2));
// What (I think) you actually want
var thisPartValue = parts[i].substring(thisPartName.length + 4);
result.push(thisPartValue);
}
else {
result.push(parts[i]);
}
}
return result;
}
Hope this helps :D

Reverse a String in JS [duplicate]

This question already has answers here:
How do you reverse a string in-place in JavaScript?
(57 answers)
Closed 7 years ago.
I'm going through tutorials to code (I'm fairly new at this), and this particular exercise is racking my brain. Here are the parameters:
Reverse the provided string.
You may need to turn the string into an array before you can reverse it. Your result must be a string.
and here is the code I'm given to start with:
function reverseString(str) {
return str;
}
reverseString('hello');
expect(reverseString('hello')).to.be.a('String');
expect(reverseString('hello')).to.equal('olleh');expected 'hello' to equal 'olleh'
expect(reverseString('Howdy')).to.equal('ydwoH');expected 'Howdy' to equal 'ydwoH'
expect(reverseString('Greetings from Earth')).to.equal('htraE morf sgniteerG');expected 'Greetings from Earth' to equal 'htraE morf sgniteerG'
Any suggestions out there on how to accomplish this?
** Edit: I figured out what my issue was. The particular IDE of the tutorial site made it confusing. Apparently I was meant to hit one of the objectives listed (not all of them in one script as I previously thought). This was accomplished by return str.split( '' ).reverse( ).join( '' );. The parameters for the split and join methods were a little confusing at first as well. Most online tutorials of this method use splitting words as an example, so I didn't realize going from
" " to ""
would change the process from reversing words to reversing letters.
Arrays have a method called reverse( ). The tutorial is hinting at using this.
To convert a string into an array of characters (in reality they're just single character strings), you can use the method split( ) with an empty string as the delimiter.
In order to convert the array back into a string, you can use the method join( ) again, with an empty string as the argument.
Using these concepts, you'll find a common solution to reversing a string.
function reverseString(str) {
return str.split( '' ).reverse( ).join( '' );
}
Pretty manual way to accomplish this
var j = 'abcdefgh';
var k = j.split('');
var reversedArr = []
for(var i = k.length; i >= 0; i--) {
reversedArr.push(k[i])
}
var reversedStr = reversedArr.join('')
console.log(reversedStr)
You can read more here: http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
A string is an array of characters, so you can use the reverse function on the array to reverse it and then return it:
function reverseString(str) {
return str.split('').reverse().join('');
}
var reversedStr = normalStr.split("").reverse().join("");

Javascript, is there a way to write an array as a single text string without commas or gaps? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
array join() method without a separator
I'm trying to code a simple array that will then be displayed as a single, continuous line of text with no comma's gaps or separations of any kind. For example, if the array was about fruit, and the fruit involved were apples[0] and bananas[1], it would be displayed as applesbananas.
I am also using socket io and tried the array.join command, but that came up as a 'native expression' in the cmd, which I wasn't sure what to do with.
This is the code I have so far:
var A = 0
var B = 0
var master = new Array();
io.sockets.on("connection", function (socket) {
socket.on("message", function (data) {
var new_data = data.split(',');
if (new_data == 'A') {
master.push(new_data)
console.log(A);
}
else if (new_data == 'B') {
master.push(new_data)
console.log(B);
}
var final = (master.join);
console.log(final);
socket.emit("message", 'master,' + final);
socket.broadcast.emit("message", 'master,' + final);
Right now, this .join expression is being displayed as a native expression in the cmd. Is there any way to join the array elements in a way the cmd or socket io will understand?
Thanks for the help!
You're seeing that error because you're missing parenthesis after your call to .join.
You can join an array with no spaces using .join('').
Try this:
var final = master.join("");

Categories

Resources