var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];
Related
I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.
I'm trying to extract user IDs from a form serialized string, here is what I have so far.
Take
var dataString = "viewUsers_length=10&id%5B%5D=8163&id%5B%5D=8188&id%5B%5D=8141"
as the example string.
I split it into an array like this
var arrStr = dataString.split(/[=&]/);
which results in an array
[0]viewUsers_length
[1]10
[2]id%5B%5D
[3]8163
[4]id%5B%5D
[5]8188
[6]id%5B%5D
[7]8141
But I only want the ids (8163, 8188, 8141)
in reality this string could contain thousands of ids in this format. I've spent some time googling so far and haven't found anything that I think will work.
Unfortunately because the parameter names for the ids are all the same, normal methods of parsing query strings might not be viable. So, this might be a job for regular expressions!
var dataString = "viewUsers_length=10&id%5B%5D=8163&id%5B%5D=8188&id%5B%5D=8141";
var regex = /&id%5B%5D=(\d+)/g;
var match;
var matches = [];
while (match = regex.exec(dataString)) {
matches.push(match[1]);
}
console.log(matches)
var list = matches.join(', ');
document.getElementById('output').innerHTML = list;
<div id="output"></div>
There are a couple of ways to address this. The first way, that I would use, would be to match the ID's with regex.
var ids = dataString.match(/id%5B%5D=[0-9]+/g);
Which would result in
["id%5B%5D=8163", "id%5B%5D=8188", "id%5B%5D=8141"]
So now we have the values, but we only want the numeric parts of it. So let's use map to remove the rest
ids = ids.map(function (id) {
return id.replace('id%5B%5D=', '');
});
The other way would just be to filter on the array you already built, but you can see that you have the 10 in the second index, which would come back as a false positive, so I think this would provide a cleaner dataset
Filter the array.
There are native JavaScript ways using Array.prototype.filter()
var dataString = "viewUsers_length=10&id%5B%5D=8163&id%5B%5D=8188&id%5B%5D=8141"
var arrStr = dataString.split(/[=&]/);
var tester = /\d{4}/;
arrStr.filter(function (item) {
return tester.test(item);
});
/*
viewUsers_length
10
id%5B%5D
8163 -Match
id%5B%5D
8188 -Match
id%5B%5D
8141 -Match
*/
As well as jQuery ways using $().filter()
Try this
var dataString = "viewUsers_length=10&id%5B%5D=8163&id%5B%5D=8188&id%5B%5D=8141";
var myRegexp = /id%5B%5D=([0-9]+)/g;
match = myRegexp.exec(dataString);
while (match != null) {
console.log(match[1]);
match = myRegexp.exec(ddd);
}
outputs
8163
8188
8141
I would split on the "&" characters, then map a function to remove everything before the "=", and finally filter to remove elements that aren't id elements. My substring function is a bit crude, and could be improved (or replaced with regex) with more knowledge of the possible values.
dataString
.split("&")
.map(function(elt){return elt.startsWith("id") ? elt.substring(9,13) : ""})
.filter(function(elt){return elt != ""})
How to cut text using jQuery? For example :
if output like :
new/2016/songs1.mp3
new/2015/songsx.mp3
new/songs3.mp3
Need output :
songs1.mp3
songsx.mp3
songs3.mp3
I want to put only file name with extension like songs-name.mp3 not directory, so i want to cut this using jQuery.
split it and take the last item
var str = "new/2016/songs1.mp3";
var items = str.split( "/" );
alert(items[items.length - 1 ]);
or simply
alert( str.split("/").pop() );
if you want to remove the rest of the text then
var str = "new/2016/songs1.mp3";
var items = str.split( "/" );
str = items[items.length - 1 ];
or
str = str.split("/").pop();
Check it out:
Here i use split function to split the string and then its return an array.
From that array we have to get the last portion i.e, Song name, So we have to get the length of that array.
After that we alert the array with the index of last portion.
var str = "new/2016/songs1.mp3";
var arr = str.split("/");
alert(arr[(arr.length) - 1]);
try this
var filepath = "new/2015/songsx.mp3";
console.log(filepath.slice(filepath.lastIndexOf("/")+1));
Using the slice method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) you can get a part of a string.
Using the lastIndexOf method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) returns the index of the last occurrence of the given string (or -1 if given string does not occur in the string).
So what we are doing is getting the slice if the file path starting with the first character after the las "/" in the filepath variable.
My url is having a parameter value as follows below:
Nr=AND(OR(abc:def),OR(ghi:jkl),OR(mno:pqr)...)
Used the below regex expression to extract the above query string successfully but it returns only the first array value For Ex. getting only abc and def value in the array.
OR\(([^:]*):([^)]*)\)
I wanted to extract all the values as two separate array values as abc,ghi,mno and def,jkl,pqr...
Plz find my code below:
var getNrValue = 'AND(OR(Analyzed:abc),OR(Compounds:def),OR(Chemical:mno))';
var regex = /OR\(([^:]*):([^)]*)\)/gm;
var s = regex.exec(getNrValue);
console.log(s);
any help on this?
You can use this regex:
([^():]+):([^():]+)
In the regex demo, the right pane shows the capture groups. There is also a live JS demo.
Use this code to create the arrays (see the output of the live JS demo):
var array1 = [];
var array2 = [];
var string = 'Nr=AND(OR(abc:def),OR(ghi:jkl),OR(mno:pqr)...)'
var string = 'Nr=AND(OR(abc:def),OR(ghi:jkl),OR(mno:pqr)...)'
var myregex = /([^():]+):([^():]+)/g;
var thematch = myregex.exec(string);
while (thematch != null) {
// add it to array of captures
array1.push(thematch[1]);
array2.push(thematch[2]);
document.write("left side: ",thematch[1],"<br />");
document.write("right side: ",thematch[2],"<br />");
// match the next one
thematch = myregex.exec(string);
}
Explanation:
([^():]+) captures to Group 1 any characters that are not parentheses ()or colons :
:
([^():]+) captures to Group 2 any characters that are not parentheses ()or colons :
the code retrieves Group 1 and Group 2 matches and pushes them onto the two arrays
Let me know if you have questions. :)
I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.