I am capturing the user`s session data into a variable and come out as the following:
"192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1"
I am trying to figure out how to capture the data after FSAPPS\ and before the = so in this case I only want to output BBF4U5C. This would be the login name of the user and may vary in lenght.
Looking for any help at this point.
Try this:
var s = "192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1"
var res = s.split("FSAPPS")[1].split("=")[0];
Here is a hackish way based on finding the start and end indexes in the string. I'm not sure what parts are reliable and what parts aren't but this will work for your specific use case.
var str = "192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1";
var start = str.indexOf("FSAPPS") + 6;
var end = str.indexOf("=1^2");
alert(str.substring(start, end));//alerts BBF4U5C
http://jsfiddle.net/7ssyub7a/
Find index of identifier (index of first letter),
find index od "=" (start looking after identifier)
with this information + known length of identifier you can easily extract sub string containing your login, (bonus points for not destroying your original string)
var txt =
"192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1";
var start = txt.indexOf("FSAPPS");
var end = txt.indexOf("=", start);
var login = txt.substring(start + 6, end);
Related
I have to extract a specific part from an url origin. But I can't seem to figure out a good and fail proof way to do this
For example, this is my url:
http://site.domain.com
I need to know what "domain" is used. How do I get this part from the url 100% of the time?
My first thought was to split it between the "." but then I thought about what could happen if someone uses a http://www.site.domain.com link. That would mean it wouldn't work.
Further explanation:
I currently have 2 website which both have a differend domain name. I have to get the information about which page is loaded, based on the "domain" name in the url.
Thanks in regard!
split the full domain name on dot and than take element before last element.
var url = 'http://www.site.domain.com';
var array = url.split(".");
var lengthOfArray = array.length;
var domain = array[lengthOfArray-2];
console.log(domain);
Split by / using split("/"):
function getDomain(url){
var arr = url.split(".");
return arr[arr.length - 2];
}
console.log(getDomain('http://site.domain.com'));
console.log(getDomain('http://www.site.domain.com'));
You could split it by "." and get the next to last text of your string.
var str = 'http://www.site.domain.com';
var domain = str.split('.');
console.log(domain[domain.length-2]);
Later Edit
To provide further fail proof, you can get the latest text between .com and the first dot before it. This will work in case you have another dot in your URL, for example: 'http://www.site.domain.com/post/test.asp'.
var str = 'http://www.site.domain.com/post/test.asp';
var preComLink = str.substr(0, str.indexOf('.com'));
var preDomainIndex = preComLink.lastIndexOf('.');
var domain = preComLink.substr(preDomainIndex + 1, str.indexOf('com'));
console.log(domain);
let code = (function(){
return{
getDomain: function(url){
var slpitDomainURL = url.split(".");
var lengthOfArray = slpitDomainURL.length;
var domain = slpitDomainURL[lengthOfArray-2];
return domain;
}
}
})();
console.log(code.getDomain('http://www.google.com'));
console.log(code.getDomain('http://www.facebook.com'));
I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).
var largePictureURL = response.d[i];
//for this example see largePictureURL
largePictureURL = "../uploads/191mapTool_thumb.png_tempLargeFileName=mapTool.png"
largePictureURL will always contain _tempLargeFileName + actual file name. Without knowing the actual file name how I can extract _tempLargeFileName + actual file name from largePictureURL?
I know how to do it with indexes but as I said I will be unsure of the name of the file. One thing for sure though I want to extract the remaining part of the string. Please advise
UPDATE #gurvinder372
//thumbNailUrlANDlargeImageUrl = "../uploads/191mapTool_thumb.png_tempLargeFileName=mapTool.png"
var largePictureURL = thumbNailUrlANDlargeImageUrl.split("_tempLargeFileName=")[1];
//largePictureURL = "mapTool.png"
var thumbnailURL = thumbNailUrlANDlargeImageUrl.split("_thumb." + "png")[0];
//thumbnailURL = "../uploads/191mapTool_thumb.png_tempLargeFileName=mapTool.png"
largePictureURL will always contain '_tempLargeFileName' + actual file
name.
This is a good enough hint to try this
var fileName = largePictureURL.split( "_tempLargeFileName" )[1]
and if = is also appended after "_tempLargeFileName" then modify the same to
var fileName = largePictureURL.split( "_tempLargeFileName=" )[1]
For getting everything before use the 0th index
var before = largePictureURL.split( "_tempLargeFileName=" )[0]
You could use substring of the index like this:
var fileName = largePictureURL.substring(largePictureURL.indexOf("_tempLargeFileName"));
That will get you everything to the end of the string, starting with "_tempLargeFileName"
I have a variable in JavaScript that holds the below value:
<label>AAA</label>
I need just the AAA. I try to replace the characters but it is failing. Would someone please suggest the best approach?
var company="<label>AAA</label>";// I am getting this value from element
var rx = new RegExp("((\\$|)(([1-9]\\d{0,2}(\\,\\d{3})*|([1-9]\\d*))(\\.\\d{2})))|(\\<)*(\\>)");
var arr = rx.exec(company);
var arr1 = company.match(rx);
if (arr[1] != null) {
var co = arr[1].replace(",", "");
}
}
As you say you need only AAA, consider the below code.
I have taken a substring between the first '>' character in the string company, added 1 to that and the last < character. However, if the company var contains more of such < or >, you could go for a regex approach.
var company="<label>AAA</label>";
alert(company.substring(company.indexOf('>')+1, company.lastIndexOf('<')));
Admittedly I'm terrible with RegEx and pattern replacements, so I'm wondering if anyone can help me out with this one as I've been trying now for a few hours and in the process of pulling my hair out.
Examples:
sum(Sales) needs to be converted to Sales_sum
max(Sales) needs to be converted to Sales_max
min(Revenue) needs to be converted to Revenue_min
The only available prefixed words will be sum, min, max, avg, xcount - not sure if this makes a difference in the solution.
Hopefully that's enough information to kind of show what I'm trying to do. Is this possible via RegEx?
Thanks in advance.
There are a few possible ways, for example :
var str = "min(Revenue)";
var arr = str.match(/([^(]+)\(([^)]+)/);
var result = arr[2]+'_'+arr[1];
result is then "Revenue_min".
Here's a more complex example following your comment, handling many matches and lowercasing the verb :
var str = "SUM(Sales) + MIN(Revenue)";
var result = str.replace(/\b([^()]+)\(([^()]+)\)/g, function(_,a,b){
return b+'_'+a.toLowerCase()
});
Result : "Sales_sum + Revenue_min"
Try with:
var input = 'sum(Sales)',
matches = input.match(/^([^(]*)\(([^)]*)/),
output = matches[2] + '_' + matches[1];
console.log(output); // Sales_sum
Also:
var input = 'sum(Sales)',
output = input.replace(/^([^(]*)\(([^)]*)\)/, '$2_$1');
You can use replace with tokens:
'sum(Sales)'.replace(/(\w+)\((\w+)\)/, '$2_$1')
Using a whitelist for your list of prefixed words:
output = input.replace(/\b(sum|min|max|avg|xcount)\((.*?)\)/gi,function(_,a,b) {
return b.toLowerCase()+"_"+a;
});
Added \b, a word boundary. This prevents something like "haxcount(xorz)" from becoming "haxorz_xcount"