get pairs of string from a string - javascript

I want from this string :
'Paris , Bruxelles , Amsterdam , Berlin'
Get this result in an array :
['Paris_Bruxelles' , 'Bruxelles_Amsterdam' , 'Amsterdam_Berlin' ]
Can anyone help me please ?

You could split the string and slice the array and get the pairs.
var string = 'Paris , Bruxelles , Amsterdam , Berlin',
array = string.split(/\s*,\s*/),
result = array.slice(1).map((s, i) => [array[i], s].join('_'));
console.log(result);

Basically in functional languages you are expected to use a zipWith function, where the accepted answer mimics that in JS with side effects.
However you may also mimic Haskell's pattern matching in JS and come up with a recursive solution without any side effects
var cities = "Paris , Bruxelles , Amsterdam , Berlin , Bayburt".split(/\s*,\s*/),
pairs = ([f,s,...rest]) => s == void 0 ? []
: [f + "_" + s].concat(pairs([s,...rest]));
console.log(pairs(cities));

Related

Javascript / Node JS - using regex to transform a string?

In my nodeJs code I make a REST call to a 3rd party api and one of the values in the response is a string value e.g:
"total": "-15"
Note that this value can either be a negative number, zero or a positive number, but as a string.
e.g:
"total": "-5"
"total": "0"
"total": "+3"
How can I convert this value to be as follows? Based off the above example:
5 under
level par
3 over
I am quite new to node/javascript - is regex the best option to do this?
As Blunt Jackson said, regex will probably be slower. Here is a conversion function example:
const toText = (value) => {
const parsed = parseInt(value)
return parsed > 0 ? `${parsed} over` : parsed < 0 ? `${Math.abs(parsed)} under` : 'level par';
}
console.log(toText("-5"));
console.log(toText("0"));
console.log(toText("+3"));
I like this question because I like Code Golf :D
So my suggestion would be this one-liner:
const toText = v => v == 0 ? "level par" : v < 0 ? `${-v} under` : `${+v} over`;
console.log(toText("-5"));
console.log(toText("0"));
console.log(toText("+3"));
Works with Numbers or Strings as parameter.

How to replace Schema «availability» string with multiple values?

I am noob with structured data implementation and don't have any code knowledge. I have been looking for a week how to solve my problem with "availability" in Google structured data testing tool.
My stocks on the front have 3 possibilities :
"Stock : 1234" (text + stock numbers)
"Stock : Coming soon"
"Stock : On demand"
Google Results example
But he problem is Goggle accept only in my case "InStock" or "OutOfStock"
I have a CSS variable element #PdtXQStock named in a variable "Product-stock"
How can have :
if "availability" string contain numbers (not is number) ==> output "InStock"
if "availability" string is "Stock : Coming soon" ==> output "OutOfStock"
if "availability" string is "Stock : On demand" ==> output "InStock"
What is the proper Custom Js function from beginning to end?
function(){
var string = {{Product-stock}};
string = "https://schema.org/InStock";
string = string.replace(/Stock : Coming Soon/g, "OutOfStock");
string = string.replace(/Stock : On demand/g, "InStock");
return string.replace;
}

How to convert selected columns of a CSV to Javascript Array

This is a small part of the CSV :-
"LEADIN","Y","0.003","0.002","3","4.27","584.99","699.59","1162.36","1587.05","4.31","1","80","Small Rutting","Small Rutting","17.8","53.71785592","-2.56060898","173.1","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","1"
"LEADIN","Y","0.008","0.007","1.42","4.41","413.34","1237.43","306.49","2743.2","4.44","1","90","Small Rutting","Small Rutting","21.7","53.71789703","-2.56059787","172.9","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","6"
"LEADIN","Y","0.013","0.012","2.02","2.6","654.11","611.97","693.14","883.1","2.77","1","70","Small Rutting","Small Rutting","25.3","53.71794075","-2.56058166","172.7","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","11"
"LEADIN","Y","0.018","0.017","1.26","6.34","478.49","1054.13","337.17","3550.75","6.34","1","100","Small Rutting","Large Radius","29.8","53.7179844","-2.56056205","172.5","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","16"
"LEADIN","Y","0.023","0.022","5.72","2.6","682.96","1180.03","1959.48","1558.87","5.72","2","100","Short Radius - Single Rut","Small Rutting","34","53.71802785","-2.56053799","172.3","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","21"
"LEADIN","Y","0.028","0.027","2.76","2.29","734.58","959.17","1120.54","1196.8","2.95","2","60","Small Rutting","Small Rutting","37.8","53.71807003","-2.56050743","172.2","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","26"
"LEADIN","Y","0.033","0.032","1.88","2.7","758.48","738.18","812.85","1119.24","2.79","1","90","Small Rutting","Small Rutting","39.8","53.71811095","-2.56047369","171.9","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","31"
"LEADIN","Y","0.038","0.037","2.85","4.13","1124.35","1150.24","1531.35","2762.81","4.21","1","90","Small Rutting","Small Rutting","40.3","53.71815122","-2.56043949","171.7","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","36"
"LEADIN","Y","0.043","0.042","9.58","3.92","1861.02","1210.96","10202.89","2443.48","9.58","2","100","Large Radius","Small Rutting","41.4","53.71819101","-2.56040444","171.4","FALSE","","04/11/2021","09:43:27","MFV_01","PG68BCU","HG","Y","41"
I want column number 16 &17 in array form.
By doing a quick google search, I found some examples of CSVtoarray function, like here : https://www.30secondsofcode.org/js/s/csv-to-array
const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
I think you can easily adapt it to solve your request.

Regular expression filter angular2

I am working on an autocomplete functionality where regex has been used for filtering. The filter code currently is as below:
filterStates(val: string) {
return val ? this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s.name))
: this.states;
}
}
Above regex worked fine for data structure like:
states=[{"name":"Alaska",code:1234},
{"name":"Bulgaria",code:12345},
{"name":"Colarado",code:12346},
{"name":"New Jersey",code:12347},
]
Heres the working plunker:https://plnkr.co/edit/Pf2pWeUYo2mt7VzwCDs2?p=preview
But now there is a slight change in the data structure as shown in the name below:
states=[{"name":"Alaska (AL)","code":1234},
{"name":"Bulgaria (BG)","code":12345},
{"name":"Colarado (CO)","code":12346},
{"name":"New Jersey (NJ)","code":12347},
]
I am not able to figure out as to how to generate the regex for name. I am a complete noob when it comes to regular expressions.
Any help would be much appreciated.
Use this regular expression to extract state name (no need to trim) : ^[\w ]+(?= \()
Alaska (AL) => match Alaska
Bulgaria (BG) => match Bulgaria
New Jersey (NJ) => match New Jersey
Here is a demo on regex101
Other possibility which will match states when you type
Replace
return val ? this.states.filter(s => new RegExp(`^[\w ]+(?= \()`, 'gi').test(s.name))
: this.states;
with
return val ? this.states.filter(s => (s && s.name && s.name.toLowerCase().substring(0, val.length) === val))
: this.states;
Here is a plunker, try to type a then l

JavaScript - Matching alphanumeric patterns with RegExp

I'm new to RegExp and to JS in general (Coming from Python), so this might be an easy question:
I'm trying to code an algebraic calculator in Javascript that receives an algebraic equation as a string, e.g.,
string = 'x^2 + 30x -12 = 4x^2 - 12x + 30';
The algorithm is already able to break the string in a single list, with all values on the right side multiplied by -1 so I can equate it all to 0, however, one of the steps to solve the equation involves creating a hashtable/dictionary, having the variable as key.
The string above results in a list eq:
eq = ['x^2', '+30x', '-12', '-4x^2', '+12x', '-30'];
I'm currently planning on iterating through this list, and using RegExp to identify both variables and the respective multiplier, so I can create a hashTable/Dictionary that will allow me to simplify the equation, such as this one:
hashTable = {
'x^2': [1, -4],
'x': [30, 12],
' ': [-12]
}
I plan on using some kind of for loop to iter through the array, and applying a match on each string to get the values I need, but I'm quite frankly, stumped.
I have already used RegExp to separate the string into the individual parts of the equation and to remove eventual spaces, but I can't imagine a way to separate -4 from x^2 in '-4x^2'.
You can try this
(-?\d+)x\^\d+.
When you execute match function :
var res = "-4x^2".match(/(-?\d+)x\^\d+/)
You will get res as an array : [ "-4x^2", "-4" ]
You have your '-4' in res[1].
By adding another group on the second \d+ (numeric char), you can retrieve the x power.
var res = "-4x^2".match(/(-?\d+)x\^(\d+)/) //res = [ "-4x^2", "-4", "2" ]
Hope it helps
If you know that the LHS of the hashtable is going to be at the end of the string. Lets say '4x', x is at the end or '-4x^2' where x^2 is at end, then we can get the number of the expression:
var exp = '-4x^2'
exp.split('x^2')[0] // will return -4
I hope this is what you were looking for.
function splitTerm(term) {
var regex = /([+-]?)([0-9]*)?([a-z](\^[0-9]+)?)?/
var match = regex.exec(term);
return {
constant: parseInt((match[1] || '') + (match[2] || 1)),
variable: match[3]
}
}
splitTerm('x^2'); // => {constant: 1, variable: "x^2"}
splitTerm('+30x'); // => {constant: 30, variable: "x"}
splitTerm('-12'); // => {constant: -12, variable: undefined}
Additionally, these tool may help you analyze and understand regular expressions:
https://regexper.com/
https://regex101.com/
http://rick.measham.id.au/paste/explain.pl

Categories

Resources