updated
I'm quite a new to this. I have looked everywhere and tried everything under the sun to fix this on my own.
My data is from a text input where i need to read specific line. My code reads the lines perfectly using the slice(2,1) method. Now I need to use the data to do other things.
my extracted string from reading data lines from 3rd line data till 2nd last line, and this already works:
var x = readData.slice(2,-1).toString();
Output using console.log(x); //0 1,2 3,4 5 as it should be
but I want: '0,1','2,3','4,5'
So that i can use this data to do other things.
I have tried:
var x = readData.slice(2,-1).toString().split(' ',-1);
this gives me: [ '0', '1,2', '3,4', '5' ] //which is the closest
i have also tried:
var x = readData.slice(2,-1).toString().replace(/\s/g, ', ').split(" ", -1); which gives [ '0,', '1,2,', '3,4,', '5' ]
var x = [x.split(' ').join(',')]; which gives [ '0,1,2,3,4,5' ]
and a few other combos too. Can anyone please help?
According to the following statement
.replace(/\s/g, ', ').split(" ", -1); which gives [ '0,', '1,2,', '3,4,', '5' ]
in the question, this 0 1,2 3,4 5 is a string, so you can split by comma and then map the strings according to the desired output
console.log("0 1,2 3,4 5".split(",").map(s => s.split(/\s+/g).join(",")));
Related
I'm trying to get the last String (from the right hand side) of the cells in a column but I cant figure it out.
I have this code that would get the first three digits from the left hand side but yeah that wont work.
var first_3_digs = values.filter(r => {
if(r.toString().includes('_')){return r;}
}).map(r=> r.toString().split('_')[0]);
For example if I want as an input CS_1*44u i want the output u. Same for ml, l etc...
If you need more info please let me know.
Thank you so much for the help.
Example how to get the 'units' from several cells:
const unit = x => /[\d]+[\D]+/.test(x) ? x.match(/[A-z]+$/)[0] : '';
var texts = ['CS_1*44u', 'Case', '72x64ml', '11x37kg', '123'];
texts.forEach(x => console.log(unit(x))); // --> 'u', '', 'ml', 'kg', ''
Example how to get the 'unit' from one cell:
const unit = x => /[\d]+[\D]+/.test(x) ? x.match(/[A-z]+$/)[0] : '';
var cell_value = 'CS_1*44u';
console.log(unit(cell_value)); // --> 'u'
If you need to get the array of the 'units' from another array of cells you can map the function this way:
const unit = x => /[\d]+[\D]+/.test(x) ? x.match(/[A-z]+$/)[0] : '';
var cells = ['CS_1*44u', 'Case', '72x64ml', '11x37kg', '123'];
var units = cells.map(x => unit(x)); // <---- here
console.log(units); // --> ['u', '', 'ml', 'kg', '']
as you have tagged formulas for possible solution, i will offer the following REGEXEXTRACT formula:
=REGEXEXTRACT(K1,"[^(\d+(\.\d+)?)(?!.*\d+(\.\d+)?)]*$")
explanation:
AFTER last occurrence of "a":
[^a]*$
LAST digit (with or without decimal):
(\d+(\.\d+)?)(?!.*\d+(\.\d+)?)
[EDIT]
where \d means a number, here is a (shorter) alternative which is also tested as working with the same dataset:
=REGEXEXTRACT(K1,"[^\d]*$")
I have a scenario like Need to edit the single quotes values (only single quotes values),
So I extracted the single quotes values using regex and prepare the reactive dynamic form.
onclick of performing edit button will show old step name above, new step name below, submit step will replace the step name in the original array.
WOrking fine as expected in few scenarios according to my approach, but in scenarios, I realized whatever algorithm I am following does not fulfill my requirement.
Below are the test cases
Test case 1:
Step Name: "Then I should hire an employee using profile '1' for 'USA'",
// Here --> '1', 'USA' values are editable
Test case 2: "And Employee should be hired on '01' day of pay period '01' of 'Current' Fiscal"
// '01', '01', 'Current'
Issues: in test case 2 if I tried to edit second 01 it is editing the first 01
I try to solve the perform edit function with help of indexof, substring functions
this.replaceString = this.selectedStep.name;
this.metaArray.forEach((element: any) => {
var metaIndex = this.replaceString.indexOf(element.paramValue);
if (metaIndex !== -1) {
const replaceValue = this.stepEditForm.controls[element['paramIndex']].value;
this.replaceString = this.replaceString.substring(0, metaIndex) + replaceValue + this.replaceString.substring(metaIndex + (element.paramValue.length));
}
});
but in indexof always find the first occurrence of a value in a string. So I realized my approach is wrong on performed it function
please find the attachment for the code
https://stackblitz.com/edit/angular-reactive-forms-cqb9hy?file=app%2Fapp.component.ts
So Can anyone please suggest to me how to solve this issue,
Thanks in advance
I added a function called matchStartingPositions that returns the starting position indexes of each match. Using this method you can then perform your edit by replacing the string just as you do, but we'll find the proper match to be replaced at the given position.
So in your line
var metaIndex = this.replaceString.indexOf(element.paramValue);
we can then add a second parameter to indexOf, that is the starting point:
var metaIndex = this.replaceString.indexOf(element.paramValue, startingPositions[element.paramIndex]);
The function for getting the index positions just looks for those single quotes in a given string:
matchStartingPositions(str) {
let count = 0;
let indices = [];
[...str].forEach((val, i) => {
if (val === "'") {
if (count % 2 == 0) {
indices.push(i);
}
count++;
}
});
return indices;
}
Here it is in action:
https://angular-reactive-forms-xhkhmx.stackblitz.io
https://stackblitz.com/edit/angular-reactive-forms-xhkhmx?file=app/app.component.ts
Hello everyone I got following code:
it('Search for string', function () {
var MySearch = element(by.model('searchQuery'));
MySearch.sendKeys('Apple Pomace');
expect(MySearch.getAttribute('value')).toBe('Apple Pomace');
element(by.buttonText('Search')).click();
//browser.pause();
var optionTexts = element.all(by.repeater('product in products')).map(function (Options) {
return Options.getText();
});
optionTexts.then(function (array){
expect(array).toContain("Apple Pomace");
});
});
then I get as result:
[ 'Apple Pomace\nFinest pressings of apples. Allergy disclaimer: Might contain traces of worms. Can be sent back to us for recycling.\n0.89' ]
now I want to check if the string contains Apple Pomace
I have tried following code:
expect(array).toContain('Apple Pomace');
then I get:
Expected [ 'Apple Pomace
Finest pressings of apples. Allergy disclaimer: Might contain traces of worms. Can be sent back to us for recycling.
0.89' ] to contain 'Apple Pomace'. <Click to see difference>
how do I set the test to true even if the whole string doesn't match my result?
or validate the string to the first "\" ?
code
Thank you in advance
First of all element.all(by.repeater('product in products')).getText() will return array of strings.If you use toContain matcher on the array, it will check for the whole string to be present in the array.
In your case, you need to check if the entire array has any string that matches the word Apple Pomace. To achieve this, you need to transform the result array into a string and then apply toContain matcher on it.
var displayedResults = element.all(by.repeater('product in products')).getText()
.then(function(resultArray){
return resultArray.join(); // will convert the array to string.
})
expect(displayedResults).toContain("Apple Pomace");
Hope this might help you!
I'm loading json file from database with two fields words and grade. Each word is graded for example true has 1 while lie has -1. Then i take input from text filed and i need to grade it based on grades from JSON file and then calculate score by summarizing the grades, but i just can't seem to find the way to do that. Words that are not in file are not being calculated.
I tried string.search match but it's to complicated and in the end i couldn't get result the way i wanted. I tried array searches same thing. I searched for on line solution, but no one has done anything similar so i can't copy it.
JSON
[
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
]
String
"Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend".
The first thing I'd do is turn your JSON data into a map which can easily be searched - key would be the word, and value the grade:
var json = [
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
];
var map = json.reduce(function(p,c){
p.set(c.word.toLowerCase(),c.grade);
return p;
}, new Map());
console.log(...map);
Then, its just a case of splitting your string, whilst also calculating the total score - again reduce can be used
var json = [
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
];
var map = json.reduce(function(p,c){
p.set(c.word.toLowerCase(),c.grade);
return p;
}, new Map());
var input = "Dogs are wonderful but i prefer cats cats i can not lie although dog is a true friend";
var score = input.split(' ').reduce(function(p,c){
var wordScore = map.get(c.toLowerCase()) || 0;
return p + wordScore;
},0);
console.log(score);
Note that I have manually removed punctuation in the above input - I'll leave that as an exercise for you.
Also note that "cats" != "cat" so some of your words wont be found!
Let's first think of the algorithm. Two options:
Search and count the input string as many times as number of words in your JSON, or
Check each word in your input string against the JSON contents.
Since the JSON length is known and (I presume) shorter than the possible input string, I would tend to prefer option 2.
Now, after selecting option 2, you need to split the input string into words and create an array containing one word each entry of the array.
You can achieve this using the mystring.split(" ") method. This, of course, does not take into account punctuations, but you can handle this using the same method.
Now, you can add to each entry in your JSON a field to count the number of appearances of each entry in the JSON within the string.
Finally, you sum the product of the counters and the grade.
console.log((function(rules, str) {
var sum = 0;
Array.prototype.forEach.call(rules, function(rule) {
var match = str.match(rule.regexp);
match && (sum += str.match(rule.regexp).length * rule.grade);
console.log([rule.regexp, match&&match.length, rule.grade, match&&match.length * rule.grade, sum]);
});
return sum;
})([{
"regexp": /true/g,
"grade": 1
}, {
"regexp": /hate/g,
"grade": -1
}, {
"regexp": /dog/g,
"grade": 0.8
}, {
"regexp": /cat/g,
"grade": -0.8
}], "Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend"));
i use regexp rather than string, u can use string and convert to regex at run time, hope this would help
I have the following array of strings. The names are locations, and each location has 4 integers "attached" to it.
Using regex (in nodeJS, with javascript), I am trying to extract the name of the location, and the last (4th) of the integers for each location.
[ ' UNICENTRO CALI 1131908 296780 133622 968750',
' PASTO 2 1044057 212780 133004 964281',
' CALIMA 1397254 311214 173761 1259801',
' PALMIRA2 922857 272954 103978 753881',
' PEREIRA CRA 6 1188885 157589 165004 1196300',
' DE LA CUESTA-BUCARAMANGA 219916 49526 27261 197651' ]
for example, for the first location I would need to fish out "UNICENTRO CALI" and "968750".
To do this, I've tried:
myArray[i].split(" ")
This separates the name of the location from the four integers, but this will turn into an inefficient mess.
Any chance somebody can do it elegantly with a regular expression?
If you aren't specifically looking for a Regex to parse your entire data, here's one way to do it easily:
var a = [ 'Total C.O. UNICENTRO CALI 1,131,908 296,780 133,622 968,750',
'Total C.O. PLAZA CAICEDO 988,721 272,182 114,641 831,180',
'Total C.O. COSMOCENTRO 692,679 159,488 85,309 618,500',
'Total C.O. PASTO 2 1,044,057 212,780 133,004 964,281'];
var b = [];
a.forEach(function(item){
var splitItem = item.split(/\s\s+/),
len = splitItem.length;
b.push({"name":splitItem[1], "value":splitItem[len-1]});
});
console.log(b);
I used the data from your Regex101 link to demonstrate in this jsFiddle.
This will capture all your columns:
/'\s+(.*\S)?\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)'/
capture group 1 = location
capture group 2 = num 1
capture group 3 = num 2
capture group 4 = num 3
capture group 5 = num 4
var str = "' UNICENTRO CALI 1131908 296780 133622 968750'";
var arr = /'\s+(.*\S)?\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)'/.exec(str);
> console.log(arr)
[Log] Array (6)
0"' UNICENTRO CALI 1131908 296780 133622 968750'"
1"UNICENTRO CALI"
2"1131908"
3"296780"
4"133622"
5"968750"
Array Prototype
Your data changed, use this:
/'(.*\S)\s+([\d,]+)\s+([\d,]+)\s+([\d,]+)\s+([\d,]+)'/
https://regex101.com/r/jJ6xM7/2
Give this a try:
/^'\s+(\w+ +\w*)( +\d+){3} +(\d+)'/
Where $1 (group 1) is your location and $3 (group 3) is the last set of integers on each line.
As I mentioned, your data from the original post changed. Use ergonaut's recommended expression:
/'(.*\S)\s+([\d,]+)\s+([\d,]+)\s+([\d,]+)\s+([\d,]+)'/