Hi I have some vars like this:
var a = Base-Shirt_Stripe.jpg
var b = Closed-Flatknit-Collar_Stripe.png
How do i create two new vars like:
var c = Base-Shirt
var d = Stripe
or
var e = Closed-Flatknit-Collar
var f = Stripe
basically split at the _ remove the _ and remove the extension.
//for example, we take a
var a = 'Base-Shirt_Stripe.jpg';
//then we take the part of a before the dot
//and split between `_`
//split returns an array
var split = a.substring(0,a.indexOf('.'))
.split('_');
//split is an array, so we use indices to indicate which
console.log(split[0]); //Base-Shirt
console.log(split[1]); //Stripe
Sample here. You can do the same for your b
may be you could do like
var a = "Base-Shirt_Stripe.jpg"
var k = a.replace(/(\.\w*)$/g, "").split("_");
alert(k[0]);
alert(k[1]);
here is the fiddle
You need to make them strings to start with, then use String.split() to split the string into an array of the different parts.
jsFiddle
var a = "Base-Shirt_Stripe.jpg"
var b = "Closed-Flatknit-Collar_Stripe.png"
var aSplit = a.substr(0, a.lastIndexOf('.')).split('_');
var c = aSplit[0];
var d = aSplit[1];
var bSplit = b.substr(0, b.lastIndexOf('.')).split('_');
e = bSplit[0];
f = bSplit[1];
You could also take the removal of the extension out into its own function using String.lastIndexOf() and String.substr().
function removeExtension(file) {
return file.substr(0, file.lastIndexOf('.'));
}
//Javascript Split can divide it into parts. Javascript Split return type is array.'
//e g.
var a = Base-Shirt_Stripe.jpg
var parts = a.split('_');
console.log(parts[0]);
//output
" Base-Shirt "
//parts[0] contain base-shirt and parts[1] contain Stripe.jpg.
Related
I'm trying to match some words in a string. But I don't have a predefined number of words I need to find.
For example I search for Ubuntu 18 10 in ubuntu-18.10-desktop-amd64.iso.torrent would return true.
Or I could search for centos 7 in CentOS-7-x86_64-LiveGNOME-1804.torrent would also return true.
I don't need to check if it's lowercase or not.
What I tried :
$.get('interdit', function(data) {
var lines = data.split("\n");
$.each(lines, function(n, data_interdit) {
var url_check = $('textarea#url').val()
var split_forbidden = data_interdit.split(/[\s|,|_|.|-|:]+/);
var exist = 0;
$.each(split_forbidden, function(n, data) {
var n = url_check.search("^("+ data +")");
if(n != -1){
exist = 1
}else{
exist = 0
}
console.log('Forbidden: '+ data + ' Result: ' + n);
})
if(exist == 1){
console.log('found')
}
});
});
Sample data of the file interdit :
CentOS.7
Ubuntu-18
You want to look for existing words within the input string without the order being taken into account. You need to use positive lookaheads for this:
var search = 'Ubuntu 18 10';
var str = 'ubuntu-18.10-desktop-amd64.iso.torrent';
var re = new RegExp('^(?=.*' + search.split(/[\s,_.:-]+/).join(')(?=.*') + ')', 'i')
console.log(re.test(str));
This produces a regex as the following (with i flag set):
^(?=.*Ubuntu)(?=.*18)(?=.*10)
RegEx Array
Update
"The code give me an error jsbin.com/pecoleweyi/2/edit?js,console"
Although the question did not include unlikely input such as: *centos 7*, add the following line to escape the special characters that occur in input:
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
and change the next line:
var sub = esc.replace(/\s/gi, '.');
The demo below will:
accept a string (str) to search and an array of strings (tgt) to find within the string,
.map() the array (tgt) which will run a function on each string (word)
escape any special characters:
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
replace any spaces (/\s/g) with a dot (.):
var sub = esc.replace(/\s/g, '.');
then makes a RegExp() Object so a variable can be inserted in the pattern via template literal interpolation (say that ten times fast):
var rgx = new RegExp(`${sub}`, `gim`);
uses .test() to get a boolean: found = true / not found = false
var bool = rgx.test(str);
create an Object to assign the search string: word as a property and the boolean: bool as it's value.
var obj = {
[word]: bool
};
returns an array of objects:
[{"centos 7":true},{"Ubuntu 18 10":true}]
Demo
var str = `ubuntu-18.10-desktop-amd64.iso.torrent
CentOS-7-x86_64-LiveGNOME-1804.torrent`;
var tgt = [`centos 7`, `Ubuntu 18 10`, `corn flakes`, `gnome`, `Red Hat`, `*centos 7*`];
function rgxArray(str, tgt) {
var res = tgt.map(function(word) {
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
var sub = esc.replace(/\s/gi, '.');
var rgx = new RegExp(`${sub}`, `gi`);
var bool = rgx.test(str);
var obj = {
[word]: bool
};
return obj;
});
return res;
}
console.log(JSON.stringify(rgxArray(str, tgt)));
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.
input:
"/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
javascript:
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
var parts = parmeters.split('[&=]');
output of my js code:
0: "passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
length: 1
i want to split my url into a map with key:value like this
output:
origin:THR
destination:TDR
goDate:2015-01-09
passengers:STANDARD:1
returnDate:2015-01-10
max:0
withThac:false
My code not do exactly what i want in output, what is wrong ?
You should split with
var params = parmeters.split('&')
and then split all the values you get
for (var i = 0,len = params.length; i<len;i++){
var data = params[i].split("=", 2); // Max 2 elements
var key = data[0];
var value = data[1];
...
}
i think your wrong ' characters
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
/*--> i think used regexp. Clear ' Char. --> */var parts = parmeters.split(/[&=]/);
use this like..
good luck
A possible solution using ECMA5 methods and assuming that your string is always the same pattern.
var src = '/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false',
slice = src.split(/[\/|?|&]/).slice(3),
data = slice.reduce(function (output, item) {
var split = item.split('=');
output[split.shift()] = split.shift();
return output;
}, {
origin: slice.shift(),
destination: slice.shift(),
goDate: slice.shift()
});
document.body.appendChild(document.createTextNode(JSON.stringify(data)));
I must have a syntax error in my code but I can't see it. fiddle here
var comma = ',,';
var stop = '.。';
var expression = '/[]+/';
expression = expression.substr(0,2) + comma + stop + expression.substr(2);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
}
I'm expecting res.length to be 3 but it is always 1 and returns the full string. What am I missing?
/ is used as delimiter for RegExp literal. e.g. /[a-zA-Z]/g
/ is not needed when you pass a pattern to the RegExp constructor. e.g. new RegExp('[a-zA-Z]', 'g')
To resolve the problem, remove the / (and modify the rest of your code):
var expression = '[]+';
Or you can just pass a RegExp literal directly:
var res = "foo,吧。baz".split(/[,,.。]+/g);
When you creat your Regex you're using this: var expression = '/[]+/';. The / delimiters are for use when you're delaring a regex like this:
var expression = /[]+/; // note: no quotes.
You're using new Regexp(), so they're not required in your string. Removing them gives this:
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}
Which does what you expect. See this fiddle. I've adjusted the string indices and the loop index so that things work...
var expression = '/[]+/';
Should be
var expression = '[]+';
Also, adjust the substring indices accordingly
http://jsfiddle.net/2Pbm3/4/
Working like this :
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}
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];