How to match a long path among plenty of short versions - javascript

SOLUTION IS :
var str = this.path;
var spltd = str.split('/');
var agg = '(?:';
var e = 'Item';
for (i = 0; i < spltd.length-2; i++) { agg += '(?:';}
var newstr = '^(?:\/?'+agg+spltd.join('\/)?')+'::)?'+e;
var regex = new RegExp(newstr);
var check = str.match(regex);
console.log(check); // Works on the good cases, not on the bad
thanks to #Rodrigo López
PROBLEM WAS :
I'm trying to setup a research functionality.
Basically, I have paths like :
Item
Path::Item
/Path::Item
Long/Path::Item
/Long/Path::Item
Very/Long/Path::Item
/Very/Long/Path::Item
Very/Very/Long/Path::Item
/Very/Very/Long/Path::Item
My/Very/Very/Long/Path::Item
There are stored into a javascript Object.
Now, I need to .match(), any of theses using the full path :
My/Very/Very/Long/Path::Item
This side is not the easier...
I've tried :
//NOTE : if it's match it returns 'OK'
var str = 'My/Very/Very/Long/Path';
var spltd = str.split('/');
var newstr = '('+spltd.join('/)?(')+')$';//alert(newstr);
var regex = new RegExp(newstr);
var check = str.match(regex);
console.log(check); // 'OK'
I can't say it doesn't work but it's still far to accurate.
It returns 'OK' in too-much cases....
Like when str =
My/Very/Long/Path::Item
My/Long/Path::Item
Very/Path::Item
etc.
Which is quite unacceptable.

Its not pretty, but this Regex does the work:
^(?:\/?(?:(?:(?:(?:My\/)?Very\/)?Very\/)?Long\/)?Path::)?Item
You can change your code to this:
var str = 'My/Very/Very/Long/Path::Item';
var regex = new RegExp('^(?:\\/?(?:(?:(?:(?:My\\/)?Very\\/)?Very\\/)?Long\\/)?Path::)?Item');
var check = str.match(regex);
Tested on Regexr.com:
Note: If its a match it returns the match, not OK, and if its not a match it returns null

Related

Select 2 characters after a particular substring in javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.
.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle
I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know
indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);
Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.
There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

Regex to get words between ":" and "," in javascript

I'm learning regex. I'm trying to get the most correct regex for the following :
Input is:
class:first,class:second,subject:math,subject:bio,room:nine
Expected output:
first,second,math,bio,nine
Want to store the above output in a string . var s = "";
Here's what I tried:
(:)(.*)(,)
However I want the last word too.
Using RegExp.prototype.exec:
var re = /:(.*?)(?:,|$)/g; // `,|$` : match `,` or end of the string.
var str = 'class:first,class:second,subject:math,subject:bio,room:nine';
var result = [];
var match;
while ((match = re.exec(str)) !== null)
result.push(match[1]);
result.join(',') // => 'first,second,math,bio,nine'
Using String.prototype.match, Array.prototype.map:
var re = /:(.*?)(,|$)/g;
var str = 'class:first,class:second,subject:math,subject:bio,room:nine';
str.match(re).map(function(m) { return m.replace(/[:,]/g, ''); }).join(',')
// => 'first,second,math,bio,nine'
Here is another method (based on the request so far):
var str = 'class:first,class:second,subject:math,subject:bio,room:nine';
// global match doesn't have sub-patterns
// there isn't a look behind in JavaScript
var s = str.match(/:([^,]+)(?=,|$)/g);
// result: [":first", ":second", ":math", ":bio", ":nine"]
// convert to string and remove the :
s = s.join(',').replace(/:/g, '');
// result: first,second,math,bio,nine"
Here is the fiddle

Get current matching regex-rule

I try to check for a given RegExp-rule in a string and need to get the current matching rule.
Here's what I've tried so far:
var prefixes = /-webkit-|-khtml-|-moz-|-ms-|-o-/g;
var match;
var str = '';
while ( !(match = prefixes.exec(str)) ) {
str += '-webkit-';
console.log(match); // => null
}
The match is null, but how can I get the current matching-rule (in this case -webkit-)?
var prefixes = /(-webkit-|-khtml-|-moz-|-ms-|-o-)/g;
var str = "-webkit-adsf-moz-adsf"
var m;
while(m = prefixes.exec(str))
console.log(m[0]);
You aren't asking for any groups in your regex, try surrounding your regex in parenthesis to define a group, e.g. /(-webkit-|-khtml-|-moz-|-ms-|-o-)/g.
Various other issues, try:
var prefixes = /(-webkit-|-khtml-|-moz-|-ms-|-o-)/g;
var match;
var str = 'prefix-ms-something';
match = prefixes.exec(str);
console.log(match);

JavaScript regex using a character twice

So I'm using regex to grab information from a string, the issue is I need to both start up and stop at a / in the string.
Here's an example
var regexp = /\/(.*?)=(.*?)\//g;
var url_hash = "/s=lorem+ipsum/p=2/";
var match;
var result = {};
while ((match = regexp.exec(url_hash)) != null) {
result[match[1]] = match[2];
}
I can grab result['s'] without issue, but grabbing result['p'] becomes problematic, because the ending / for result['s'] is the same as the starting / for result['p']. If I changed the string to /s=lorem+ipsum//p=2/ it works perfectly, but of course that's hideous. So how can I fix this so that it both ends and starts up at the /? I'm stuck, any help is appreciated.
Use this regex:
/\/([^/=]+)=([^/]+)/
Code:
var regexp = /\/([^/=]+)=([^/]+)/g;
var url_hash = "/#!/s=lorem+ipsum/p=2/";
var match;
var result = {};
while ((match = regexp.exec(url_hash)) != null) {
result[match[1]] = match[2];
document.writeln(match[1] + ' = ' + match[2] + '<br>');
}
OUTPUT:
s = lorem+ipsum
p = 2
Online demo of the code
Why can't you just split it?
var result = {};
var url = "/#!/s=lorem+ipsum/p=2/".slice(4, -1).split('/');
for (i in url) {
var value = url[i].split('=');
result[value[0]] = value[1];
}
console.log(result);
You can determine the look-ahead set for part after the = yourself instead of adding it to the regular expression. The look-ahead set is "everything but a forward slash".
var regexp = /\/(\w+)=([^/]+)/g;
Btw, I'm assuming that the part before the = is word-like (i.e. alphanumeric)

Parse out all long/lat from a string

Hi i am trying to get each longitude and latitude that arrives in this format:
(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)
I wish to store them in these strings tmpLon1 tmpLat1 tmpLon2 tmpLat2 tmpLon3 tmpLat3 tmpLon4 tmpLat4
So far i have done this coding but it fails to work, any body have a better method and could code up an example please ?
//(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)
//Remove all the shit
longlat = (longlat.replace(/\(/g,""));
longlat = (longlat.replace(/\)/g,"|"));
longlat = (longlat.replace(/\ /g,""));
//52.99315484540412,-1.179145092694469|52.99315323095451, -1.1786797294303852|52.993042641012025, -1.1789238104507405|52.99308461678997, -1.1791705736801106|
//Now split out each long lat
tmpLon1 = longlat.split(",","1"); //ok
tmpLat1 = longlat.replace(tmpLon1 + ",","");
tmpLon2 = tmpLat1;
tmpLat1 = tmpLat1.split("|","1"); //ok
tmpLon2 = tmpLon2.split("|","2");
tmpLon2 = tmpLon2.replace(tmpLat1,"");
tmpLat2 = longlat.split(",","4");
tmpLon3 = "";
tmpLat3 = "";
tmpLon4 = "";
tmpLat4 = "";
I'd do this:
var a = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)",
latLngs = [],
pairs = a.replace(/^\(|\)$/g,'').split(')(');
for(var i=0,pair;pair=pairs[i];i++) {
pair = pair.split(',');
latLngs.push({lat: +pair[0], lng: +pair[1]});
}
console.log(latLngs);
you can see it live here: http://jsfiddle.net/LCYrg/
You could also simply do:
var a = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)",
JSON.parse(a.split(')(').join('],[').replace('(','[[').replace(')',']]'));
But this would require the JSON object to be present, which is not the case in ie7 and below. This could be fixed by including the json2.js file found here: https://github.com/douglascrockford/JSON-js
Regex to the rescue! Since you know the format of your string, you can use regex here to search for you.
var str = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, 1.1789238104507405)(52.99308461678997, -1.1791705736801106)";
var regex = /\((-?[0-9]+\.[0-9]+), (-?[0-9]+\.[0-9]+)\)/g;
var latlonArray = [];
var match = regex.exec(str);
while (match) {
latlonArray.push({
"lat" : match[1],
"lon" : match[2]
});
match = regex.exec(str);
}
var tmpLon1 = latlonArray[0].lon;
var tmpLat1 = latlonArray[0].lat;
var tmpLon2 = latlonArray[1].lon;
var tmpLat2 = latlonArray[1].lat;
var tmpLon3 = latlonArray[2].lon;
var tmpLat3 = latlonArray[2].lat;
var tmpLon4 = latlonArray[3].lon;
var tmpLat4 = latlonArray[3].lat;
Example: http://jsfiddle.net/jonathon/57rE4/
The latlonArray is an array of objects with lat and lon properties, containing the ones found in your string.
Note: the regex I used here is just something I came up with. It works with your example input but might not necessarily be the best.
Also note: this isn't meant to be 'pull out and use' JavaScript. It's merely showing you another way to do it. I'd recommend optimising it by various means (e.g. moving all vars to the top, etc).
i guesy u can do something like:
(assuming input is your input string)
input = input.replace(/\s/,''); //remove spaces
var pairs_strings = input.substring(1,-1).split(")("); //remove braket of start and end and then split into pairs
var pairs = new Array();
for(var i=0; i<paris_strings.length; i++){
lon = pairs_strings[i].split(",").shift();
lat = pairs_strings[i].split(",").pop();
pairs[i] = new Array(lon, lat);
}
var tmpLon1 = pairs[0][0];
var tmpLan1 = pairs[0][1];
....
but be aware it's not tested and i don't know what will happend with the negative values
If your input format is not changing you could do it in 3 lines:
var str = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)";
var pattern = /([\d\.-]+),\s([\d\.-]+)\)\(([\d\.-]+),\s([\d\.-]+)\)\(([\d\.-]+),\s([\d\.-]+)\)\(([\d\.-]+),\s([\d\.-]+)/;
var result = str.match(pattern);
To get the results use:
tmpLon1=result[1];
tmpLon2=result[3];
tmpLon3=result[5];
tmpLon4=result[7];
tmpLat1=result[2];
tmpLat2=result[4];
tmpLat3=result[6];
tmpLat4=result[8];
var str = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)";
var str = str.replace(/\)\(/g,', ').replace(/\(|\)/g,'').split(", ");
To get the results:
tmpLon1=result[0];
tmpLon2=result[2];
tmpLon3=result[4];
tmpLon4=result[6];
tmpLat1=result[1];
tmpLat2=result[3];
tmpLat3=result[5];
tmpLat4=result[7];

Categories

Resources