conditional splitting of string and word by matching characters in js - javascript

I have very long string that contains html as a string , numbers , my special bindings and numbers I want to split my bindings and sentences with spaces separately but my program is separately my bindings and words .
my js code:-
var x = 'hey this is {{name}} and I love to {{write}} and to learn as
much as I can. Now I am trying to separate sentences and my bindings'
var c = x.match(/\s*\S*\s*/g) // this splits words from string including
space
var mt = x.match(/{(.*)}/g); // trying to take out bindings but this don't
work
mt.forEach(function(a){ // taking each bindings separately
var z = x.match(a)
})
console.log(mt)
Somthing like this .. but I know this is totally wrong please help me
I don't have any idea :-
output that I am expecting:-
(5) ["hey this is", "i", "{{name}}", " and I love to ", "{{write}}", " and to learn as ↵ much as I can. Now I am trying to separate sentences and my bindings"]
How can i do this?
Please don't use jquery

Try this:
I've commented my code hoping it would make it easier to read. But do note that this code is far from perfect although it solves your problem.
var rawString = 'hey this is {{name}} and I love to {{write}} and to learn as much as I can. Now I am trying to separate sentences and my bindings';
var arrayRawString = rawString.match(/\s*\S*\s*/g); // this splits words from string including space
var arrayPlaceholder = rawString.match(/{(.\S*)}+/g); // trying to take out bindings but this don't work
// to store the final output
var separedArray = [];
// keeping track of the index to stich the array up
var posStart = 0;
var posEnd = 0;
arrayPlaceholder.forEach(function(arg){ // taking each bindings separately
// length of the array that holds placeholder (bindings)
var arsLength = arrayRawString.length;
for(var i = 0; i < arsLength; ++i) {
// if the provided text matches the original array's element
if(arrayRawString[i].match(arg)){
// to store the index
posEnd = arrayRawString.indexOf(arrayRawString[i]);
// join the pieces together upto the index defined
var res = arrayRawString.slice(posStart, posEnd).join('');
// to indicate whether the stored string is the placeholder
var flag = true;
// store the string obtained
separedArray.push(res.replace(arrayPlaceholder[(arrayPlaceholder.indexOf(arg) - 1) < 0 ? 0 : arrayPlaceholder.indexOf(arg) - 1 ], ''));
// check if the string still has placeholder (bindings)
// to remove it
for(var j = 0; j < arg.length; ++j) {
if(res[j] !== arg[j]) {
flag = !flag;
}
}
if ( flag ) {
separedArray.push(arg);
}
// last end position is the start position for next round
posStart = posEnd;
// because the loop runs only arrayPlaceholder.length times
// it solves the problem of last part not getting pushed to the final array
if( arrayPlaceholder[arrayPlaceholder.length-1] === arg ) {
res = arrayRawString.slice(posStart, arrayRawString.length).join('');
separedArray.push(res.replace(arg, ''));
}
}
}
});
console.log(separedArray);

Related

How do I search through an array using a string, which is split into an array?

I currently have a half solution to this, but I was wondering if there is a better way to write this. I have the following array with equipment deliveries:
var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59",etc....]
Which I search through using an input:
var pn = document.getElementById("PN").value;
pn = pn.split(" ");
What I'm trying to achieve is to split the search word with spaces, and check if an index in the array contains all of these words. I currently search up to three words, since the code would become too long using my "solution", if I searched for more. This is my code:
var sArray = []//search results
for(var i = 0; i < deliveries.length; i++){
if (pn.length == 2) {
if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])) sArray.push(deliveries[i]);
}
else if (pn.length == 3) {
if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])&& new RegExp(pn[2],"i").test(deliveries[i])) sArray.push(deliveries[i]);
}
else {if(new RegExp(pn[0],"i").test(deliveries[i])) sArray.push(deliveries[i])};
}
What would be the correct way to search using all the words in the pn array?
I tried saving the if statements as a string, adding code to the string for each index of pn and then using eval. This turned out to slow the search to a crawl though.
Any help would be appreciated.
Example added for a user searching for "cub a32":
pn = "cub a32"
Which turns into:
pn = ["cub, "a32"]
Results in:
sArray = ["14/02/2020, 11:47,cubicles,A32"]
You could filter the array and check with every or some, depending if you want all or just one search string in an item of deliveries.
var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59"],
input = "cub a32",
pn = input.toLowerCase().split(' '),
result = deliveries.filter(s => pn.every(v => s.toLowerCase().includes(v)));
console.log(result);

JavaScript Search and Loop - doesn't return correct values

Please, can you check my code where is the error? It should loop trough 1 array to choose each string and then loop through second array and check, if the value from second string contains value of first string.
for (var i = 0; i < oldLines.length; i++){
var subStringEach = oldLines[i];
var subStringEachNoDash = subStringEach.replace(/[^a-z0-9]/g,'');
// read New URLs and line by line save them as an object
var newLines = $('#newUrl').val().split(/\n/);
var newUrlResult = [];
for (var j = 0; j < newLines.length; j++){
var newUrlString = newLines[j];
var newUrlStringNoDash = newUrlString.replace(/[^a-z0-9]/g,'');
var isThere = newUrlStringNoDash.search(subStringEachNoDash);
if (isThere !== -1 ) {
newUrlResult[i] = newLines[j];
}
else {
newUrlResult[i] = "";
}
}
stockData.push({OldURL:oldLines[i],SearchSubstring:subStringEach,NewURL:newUrlResult[i]});
}
Now it finds only part of the results.. I place to first array:
anica-apartment
casa-calamari-real
ostrovni-apartman
and to the second array:
http://tempweb3.datastack.cz/be-property/anica-apartment/
http://tempweb3.datastack.cz/be-property/ostrovni-apartman/
http://tempweb3.datastack.cz/be-property/st-michael-apartment/
http://tempweb3.datastack.cz/be-property/casa-calamari-real/
and it will only find and return casa-calamari-real, http://tempweb3.datastack.cz/be-property/casa-calamari-real/ and the others returns empty..
Any ideas please?
Here is the full code on Codepen: https://codepen.io/vlastapolach/pen/VWRRXX
Once you find a match you should exit the inner loop, otherwise the next iteration of that loop will clear again what you had matched.
Secondly, you should use push instead of accessing an index, as you don't know how many results you will have. And as a consequence you will need to relate the find string with it (because i will not be necessary the same in both arrays)
So replace:
if (isThere !== -1 ) {
newUrlResult[i] = newLines[j];
}
else {
newUrlResult[i] = "";
}
with this:
if (isThere !== -1 ) {
newUrlResult.push({
searchSubstring: subStringEach,
newURL: newUrlString
});
break; // exit loop
}
At the end, just output newUrlResult.
NB: If you want to leave the possibility that a search string matches with more than one URL, then you don't need the break. The push will then still prevent you from overwriting a previous result.
I see that you solved already) But maybe you will like this code too)
newUrlResult variable could be a string I guess, because loop breaks when one value is found. If no values where found there will be just empty string. And I'm not sure you need to call newLines = $('#newUrl').val().split(/\n/) on every iteration.
var stockData = [];
oldLines.map(function(oldLine){
var cleanOldLine = oldLine.replace(/[^a-z0-9]/g,''),
newLines = $('#newUrl').val().split(/\n/),
newUrlResult = '';
for (var j = 0; j < newLines.length; j++){
var newLine = newLines[j],
cleanNewLine = newLine.replace(/[^a-z0-9]/g,''),
ifExists = cleanNewLine.search(cleanOldLine);
if (ifExists !== -1) {
newUrlResult = newLine;
break;
}
}
stockData.push({OldURL:oldLine, SearchSubstring:cleanOldLine, NewURL:newUrlResult});
});

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

How to get string in regular expression with space

This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}

reading all the submatches in regexp multiple matches

today i'm trying to parse a 'ps aux' output (issued from a node.js server)
so i made an happy regex to parse the values, and i wanted to put all those fancy informations into a simple JSON object :-)
problem is, the regex i've made has 3 match groups, doing multiple matches... and i don't even know if it's possible to have it all the matches returned.
var spawn = require("child_process").spawn;
function exec(http_req, http_resp){
var re_ps = /(?:([\d\.\w\-\?\/\+]+)\s+){8}(?:((?:\d+\:\d+)|(?:\w+\d+))\s+){2}([^\n]+)/g,
result_re_ps,
array_re_ps = [];
//[USER, PID, %CPU, %MEM, VSZ, RSS, TTY, STAT], dates[START, TIME], COMMAND
var ps_process = spawn("ps", ["aux"]);
ps_process.stdout.on("data", function(data){
var split_data = data.toString().split('\n');
for (var i=1; i < 2; i++){
while ((result_re_ps = re_ps.exec(split_data[i])) != null){
console.log("--- while iteration ---");
console.dir(result_re_ps);
//console.dir(result_re_ps);
}
}
//http_resp.write(data);
});
ps_process.on("exit", function (code) {
if (code !== 0) {
console.log("ps_process exited with code " + code);
}
http_resp.end();
});
}
exports.exec = exec;
the "--- while iteration ---" it's just one per each line, instead, it should be multiples!
I will link a fancy screenshot to let you visually understand what kind of data i'm expecting
As you can see the above are 3 groups of data, each one with multiple occurrences
Any help? :p
EDITED TO CLARIFY:
This is the result of a line like:
root 5213 0.0 2.1 8688 2760 ? Ss 11:33 0:01 sshd: root#pts/0
As you can see, the resulting array is 1-dimensional, instead for the results to be contained entirely it HAS to be at least 2-dimensional
UPDATE:
For now i've solved the problem changin my code like this:
var spawn = require("child_process").spawn;
function exec(http_req, http_resp){
var array_re_ps = [];
var re_ps1 = /(?:([\d\.\w\-\?\/\+]+)\s+)/g,
re_ps2 = /(?:((?:\d+\:\d+)|(?:\w+\d+))\s+)/g,
re_ps3 = /([^\n]+)/g;
//[USER, PID, %CPU, %MEM, VSZ, RSS, TTY, STAT], dates[START, TIME], COMMAND
var ps_process = spawn("ps", ["aux"]);
ps_process.stdout.on("data", function(data){
var split_data = data.toString().split('\n');
for (var i=20; i < 21; i++){
array_re_ps[0] = [], array_re_ps[1] = [];
for (var j=0; j<8; j++){
array_re_ps[0].push(re_ps1.exec(split_data[i])[1]);
}
re_ps2.lastIndex = re_ps1.lastIndex;
for (var j=0; j<2; j++){
array_re_ps[1].push(re_ps2.exec(split_data[i])[1])
}
re_ps3.lastIndex = re_ps2.lastIndex;
array_re_ps[2] = re_ps3.exec(split_data[i])[1];
console.dir(array_re_ps);
}
});
ps_process.on("exit", function (code) {
if (code !== 0) {
console.log("ps_process exited with code " + code);
}
http_resp.end();
});
}
exports.exec = exec;
Basically i split my long regexp, in 3 smaller ones, and i do cycle through their results.
If you try the code i formatted the resulting array exactly as i wanted, but i still think that it's a side-solution.
Since Regular Expressions lets you "multiple parse group multiple times", it is possible to have that functionality in javascript?
Take a look at the return values of the exec function.
It returns the index where it first matched, the original string and the capture groups in the elements [0]...[n].
All this is available in your output, you just have to iterate through the single elements of the array.

Categories

Resources