Get String value between two strings through javascript - javascript

I want to get the string value between ";L0|" and ";GTSet" from the following type of strings.
var test = "GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
var test2 = "GP0|#15a06b93-f7aa-4dda-b0d6-7bf2d2905f27;L0|#015a06b93-f7aa-4dda-b0d6-7bf2d2905f27|Special Event;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
Here is what i have done already.
var str = test2.match(";L0|" + "(.*?)" + ";GTSet");
alert(str[1]);
and this returns a string from the very beginning till the ";GTSet"
Jsfiddle link here

I guess you are getting this value from SharePoint Search results, right? If so, according to Automatically created managed properties in SharePoint Server 2013:
Data format for Managed Metadata.
To query for items tagged with a Managed Metadata field, you have to
use the Unique Identifier for each label. You can find the Unique
Identifier for each term in a term set in the Term Store Management
Tool, on the GENERAL tab. In addition, the data format that is used in
the query has to specify from which level in the term set the query
should apply. This specification is set by adding one of the following
prefixes to the Unique Identifier:
To query for all items that are tagged with a term: GP0|#
To query for all items that are tagged with a child of term: GPP|#
To query for all items that are tagged with a term from a term set: GTSet|#
Based on this information the following example demonstrates how to parse search result value for managed metadata:
function parseTaxonomySearchResultValue(val){
var taxValue = {TermSetGuids: [], TermValues: []};
var parts = val.split(';');
parts.forEach(function(part){
if (part.startsWith("GP0|#")) //term?
{
var termGuid = part.replace("GP0|#", "");
taxValue.TermValues.push({ TermGuid: termGuid});
}
else if (part.startsWith("GTSet|#")) //term set?
{
taxValue.TermSetGuids.push(part.replace("GTSet|#", ""));
}
else if (part.startsWith("L0|#")) //Term with label?
{
var termParts = part.replace("L0|#0", "").split('|');
var termGuid = termParts[0];
var termLabel = termParts[1];
var result = taxValue.TermValues.filter(function(tv){
return tv.TermGuid == termGuid;
});
if (result.length == 0)
taxValue.TermValues.push({TermGuid : termGuid, Label : termLabel});
else
result[0].Label = termLabel;
}
});
return taxValue;
}
//Usage
var taxValue = 'GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc';
var taxValue = parseTaxonomySearchResultValue(taxValue);
document.getElementById('output').innerHTML = "Term info:<br/>" + "Guid= " + taxValue.TermValues[0].TermGuid + "<br/> Label= " + taxValue.TermValues[0].Label;
<div id='output'/>

Related

Using JS to sum a column of values from an external text file containing donation histories of a db of donors

I need some assistance figuring out how to sum a column of dynamic totals that could be a positive or negative dollar amount, or an indication of stock shares.
I have a tab-delimited text file of donor contributions for that I am matching up against a CSV file of other related customer data that I am using to create a statement letter which will show a "donation history" of a particular donor. Each donor has a different amount of donations, and to complicate things, the column of data for a particular donation record could show either "$1,000.00" or "($1,000.00)" or "2 Shares APPL". The number with the parentheticals is of course, representing a negative number.
At the end of this column, I need to show a string that will read either "Total: $1,000.00," or if any of the donation history contains a donation record that included shares of stock the returned string will simply read, "$1,000.00 & Stock."
I have been racking my brain trying to come up with the JS rule that can achieve this. I have the JS rule that is generating the donation history correctly, but summing the donation amount column is causing me to go crazy...
Here is the JS for generating my donation history list in the letter (this seems to be working fine):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
var lb = "<br>\n";
var matches = new Array();
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var dateVariable = contributionList.GetFieldValue(i, "Donation Date");
var ministryVariable = contributionList.GetFieldValue(i, "Ministry Designation");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
if (donor_id == idVariable)
matches.push(tsSettings + dateVariable + ts + giftVariable + ts + ministryVariable);
}
//return matches;
return matches.join(lb);
Now here is the JS code that is not working just fine. I am trying to tally the donation amount column, it only returns "Total: $0.00 & Stock" every time (I have tried to explain my thought process via comments):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var sum = 0;
var shares = 0;
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
var totalStr = "Total ";
var stockStr = " & Stock";
var totalFormatted = FormatNumber("$#,###.00", Math.max(0, StringToNumber(sum)));
// Match data from linked file to current Supporter
if (donor_id == idVariable) {
// Look at current record and see if it contains the word "Share(s)"
// or not and act accordingly
if (giftVariable.match(/(^|\W)share($|\W)/i) || giftVariable.match(/(^|\W)shares($|\W)/i)) {
// Turn switch "on" if donation amount is a share or shares so
// we can have the " & Stock" appended to our string.
shares = 1;
// Because this donation is/are shares, we must "zero" this
// amount to make the math work when we sum everything up...
giftVariable = 0;
// This is where we are keeping our running total...
sum += giftVariable[i];
} else {
// This record was not a donation of share(s) so we now have to
// determine whether we are dealing with postive or negative numbers
// and then strip out all of the non-number characters, remove and
// replace the () whis just a "-," leaving us with a number we can
// work with...
// If number has parenthesis, then deal with it...
if (giftVariable.indexOf("(")) {
// Strip out all the ()$, characters...
giftVariable = giftVariable.replace(/[()$,]/g,"")
// Append the minus sign to the number...
giftVariable = "-" + giftVariable;
sum += giftVariable[i];
} else {
giftVariable = giftVariable.replace(/[$,]/g,"");
sum += giftVariable[i];
}
}
}
}
// Return Total...
if (shares == 1) {
return tsSettings + totalStr + ts + totalFormatted + stockStr;
} else {
return tsSettings + totalStr + ts + totalFormatted;
}
Any assistance would be greatly appreciated!
The problem (and code) needs to be broken into smaller, atomic steps. From your description it sounds like you should:
load a text file into memory
for each line in the file
extract: {
donor_id
charity
gift
and store the results in a contributions dictionary
for each item in the contributions dictionary
transform gift string into {
dollarAmount: float with a default of 0.0
stock: name with a default of ""
}
create an empty dictionary called totals
each item will have the shape {
id
dollarAmount as a float
stocks an an array
}
for each item in the contributions dictionary
lookup the id in the totals dictionary
if it exists
totals[id].dolarAmount += item.dollarAmount
totals[id].stocks.push(item.stock)
otherwise
totals[id].dollarAmount = item.dollarAmount
totals[id].stocks = [item.stock]
normalize your charities
for each item in totals dictionary
remove any empty strings from item.charities
create your report
for each item in totals dictionary
write`${item.id} donated `${item.dollarAmont}` ${item.stocks.length > 1 ? 'and stock' : ''
I believe you are trying to do too many things at once. Instead, the goal should be to normalize your data before you attempt to perform any calculations or aggrgrations, then normalize your aggregrations before writing your summaries or reports.
I would also stay away from using any direct string manipulation. You should have a dedicated function whose only purpose is to take a string like "($20.34) and 1 share of APPL" and return either 20.34, -20.34, or 0.0. And a different function whose only purpose is to take the same string and return either true or false is stock was present.

Iterate over a URL and add/replace string if needed

I have an eCommerce Shopify URL that I need to check for a particular string to determine to change the currency or not.
When the user lands on the site, the URL is e.g. https://www.myshop.com.
In the navigation bar, there are buttons that allow the user to change from the default USD currency to their local currency.
This is a native Shopify feature that requires you to add ?currency=GBP (for example to British Pounds) to the URL.
I check if the string ?currency= exists, and if it does it means the user has selected a currency already, but want to change it again. So I strip out 13 characters from the start of the ? and then replace it with the new currency string.
The problem is if someone lands on the site from an ad, the URL might look like https://www.myshop.com?HkuhJKh6876MJ.
Then I have to change the currency URL to & instead of ?
I can iterate over the string and check for more than 1 ? and then change the URL, but it seems long-winded. Is there a better way to do this?
Below is my current code to check for the ?currency= substring and remove and replace it if it exists with a new currency.
<input type="button" value="Show USD" onclick="showUSD()">
<input type="button" value="Show GBP" onclick="showAUD()">
<script>
function showUSD() {
var changeToCurrency = "USD"; // Set selected currency
checkForSubstring(changeToCurrency); // Check for '?currency=' substring
}
function showGBP() {
var changeToCurrency = "GBP";
checkForSubstring(changeToCurrency);
}
// Check for substring
function checkForSubstring (newCurrency) {
var urlString = window.location.href + "";
var currencySubstring = "?currency=";
if ((urlString.includes(currencySubstring))) {
sliceURL(urlString, currencySubstring, newCurrency);
}
else {
alert("Doesnt contain substring. \nLoading new URL.");
window.location.replace(urlString + currencySubstring + newCurrency);
}
}
// Slice URL
function sliceURL (originalURL, stringToSlice, currency) {
var n = originalURL.indexOf(stringToSlice); // Get position of substring
// Slice substring from URL
var S = originalURL + "";
var bindex = n;
var eindex = n + 13;
S = S.substr(0, bindex) + S.substr(eindex);
// Reload new URL
reloadURL(S, stringToSlice, currency);
}
// Reload URL
function reloadURL(baseURL, stc, currency) {
window.location.replace(baseURL + stc + currency);
}
</script>
The method below will replace the currency value in the query string if there is currency present in window.location.search
let updateCurrency = (CUR)=>{
let queryString = window.location.search;
if(queryString && queryString.length){
queryString = queryString.slice(1);
queryStringData = queryString.split("&");
queryStringData.forEach((query,index)=>{
query = query.split("=")
if(query[0]== 'currency'){
queryStringData.splice(index,1);
queryStringData = queryStringData.join('&')
window.location.search =queryStringData +'&currency='+CUR
}
});
}
}

How can I convert a twitter user ID into a user name in Javascript/jQuery

I have a twiter web app that I am building. It is following a select group of twitter IDs and only picking out tweets that they post based on again a select group of keywords. Everything is working fine except I want to convert the twitter ID i have in an array into the corresponding twitter user name (one by one) so for example the array of IDs is var trackedHandles; and i want to convert trackedHandles[i] to a user name and print it the console next to the actual tweet. SO it would look like this in the console: #me: here is my tweet Here is my code selection that relates to this:
t.stream(
"statuses/filter",
{track: trackedHandles + trackedWords, lang: "en" },
function(stream) {
stream.on('data', function(tweet) {
for (var i= 0; i < trackedData.length; i++) {
if(tweet.text.indexOf(trackedData[i]) > - 1) {
// incriments added value to the word
redisClient.incr(trackedData[i]);
console.log(trackedHandles[i] + ":" + " " + tweet.text + " " );
//console.log(trackedData[i]);
}
}
});
}
);
Right now i'm just printing the twitter ID, but again I want to print the username. I appreciate your help.
I figured it out on my own! In case someone in the future needs to know how though:
//Get Screen_Name from tweet object.
function getPosition(str,m, i) { //special helper function to find the nth position of a string.
return str.split(m, i).join(m).length;
}
var snStartingPos = getPosition(tweetObject, "screen_name", 2); //starting position of "screen_name" in tweet object.
var snEndingPos = snStartingPos + 14; //ending position of "screen_name" in tweet object (where we actually want to start).
var unStartingPos = getPosition(tweetObject, "location", 1); //starting position of the word after where we want to end.
var unPrePos = unStartingPos - 3; //subtract that by 3 characters to exclude the unnecessary characters
var snLength = unPrePos - snEndingPos; //this is now the length of the screen_name we want
var screen_name = "#" + tweetObject.substr(snEndingPos, snLength); //get the sub-str that we want (the "screen_name") from tweet object.
//End Get Screen_Name from tweet Object
tweetObject is just tweet converted as a string. the function getPosition, I got off another stackOverflow question page: How to get the nth occurrence in a string?

JavaScript: extract column headers from table configuration string

I need help grabbing some string operation in Javascript. I have a sample string as
var str = 'Supplier^supp^left^string*Spend (USD MM)^spend^right^number^5';
The string is basically a configuration for a portlet for two columns as Supplier and Spend..I have to get the column names from this string. Each star follows a new column config. In this case there are configs for only 2 columns and hence only 1 star exists in my string. Supposedly if there are 2 columns the string will look like
var str = 'Supplier (Name)^Supplier^left^string*Spend (USD MM)^Spend^right^number^5*Location (Area)^Loc^right^string^*Category ^Categ^right^string';
So from the above string i had written a logic to get the desired string as
after the 2nd caret i want 'Supplier'(1stcolumn data name and not 'Supplier (Name) which is a display name) ,(Moving to 2nd column after the star)after the 2nd caret 'Spend'.Similarly 'Loc' (3rd column) and 'Categ' (4th column). Can anybody help me achieve this? Here is what i had written
function getColNamesfromConfig(str) {
var i = str.indexOf('^');
var tmpCatStr = str.slice(i + 1);
var catField = tmpCatStr.slice(0, tmpCatStr.indexOf('^'));
var j = tmpCatStr.indexOf('*');
var tmpStr = tmpCatStr.slice((j + 1));
var k = tmpStr.slice(tmpStr.indexOf('^') + 1);
var valField = k.slice(0, k.indexOf('^'));
return { categoryField: catField, valueField: valField };
}
You can use split()
str.split('*')[0].split('^')[1]
the above code will give you
Supplier
Check the following link
Or use a regular expression:
function headers(s) {
var re = /([^^]+)(?:[^*]+[*]?)?/g, names=[];
while (match = re.exec(s)) {
names.push(match[1]);
}
return names;
}
Outputs
["Supplier","Spend (USD MM)","Location (Area)","Category "]
and
["Supplier (Name)","Spend (USD MM)","Location (Area)","Category "]
for your two examples
See this in action (JSFiddle).

How do I simplify this repetitive jquery code?

I made a jQuery script that works fine, I'd just like to see if anyone had tips on simplifying it, in particular the beginning part in which variables are defined.
Though I'm really interested in straight code simplification, here's a quick synopsis on what the script actually does:
Looks for links with a class of 'tour' and defines 3 more variations of its href attribute (swapping out a 4-digit number).
Replaces links with a class of 'tour' with different content that substitutes in the additional 4-digit values.
With a.tour replaced, visibility of part of the content is toggled on hover.
And here's the code:
HTML:
Link
JQUERY:
<script>
$(document).ready(function() {
var aud = $('.tour').attr('href');
var usd = $('.tour').attr('href').replace(7838,'8062');
var gbp = $('.tour').attr('href').replace(7838,'8907');
var eur = $('.tour').attr('href').replace(7838,'8914');
$('.tour').replaceWith('<div class="currency"><p>Price & Bookings</p><ul class="currencydd" style="display:none"><li>Australian Dollar (AUD)</li><li>United States Dollar (USD)</li><li>British Pounds (GBP)</li><li>Euros (EUR)</li></ul></div>');
$('.currency').hover(function () {
$('.currencydd').slideToggle("fast");
});
});
</script>
Don't keep using $(".tour") over and over, it is both neater and more efficient to define a variable equal to it. Also, you don't need to keep checking the .attr("href") because once you've stored that value in aud you can use that:
var $tour = $(".tour"),
aud = $tour.attr('href'),
usd = aud.replace(7838,'8062'),
gbp = aud.replace(7838,'8907'),
eur = aud.replace(7838,'8914');
$tour.replaceWith(...);
Note that your code will update (replace) all .tour links using the aud, usd, etc. values from the first .tour link. Is that what you intend, or should it update them individually?
well for starters you could have the following:
var $aud = $('.tour').attr('href'),
$usd = $aud.replace(7838,'8062'),
$gbp = $aud.replace(7838,'8907'),
$eur = $aud.replace(7838,'8914');
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var usd = treplace('8062');
var gbp = treplace('8907');
var eur = treplace('8914');
Even better, you can do something like this if you want lots of currencies
var abbrev=["USD","GBP","EUR"]
var codes=[8062,8907,8924]
var names=["US Dollar","British Pounds","Aussie Dollar"]
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var s='<div class="currency"><p>Price & Bookings</p><ul>';
for(i in abbrev){
//build the rest of the HTML here, using the arrays
}
s+='</ul></div>'
$('.tour').replaceWith(s)
You could also use a 2D array or a custom object instead of three arrays.
2 suggestions:
1: write a function for url transformation
such as
function currencyExchange(srcUrl){
return srcUrl.substring(0,preLength) + rate * Number(src.substring(preLength));
}
2: using javascript template technique to simply the new element construction.
This is not shorter but definitely more optimized and more extensible. Untested:
var href = $('.tour').attr('href'),
items = '',
currency = {
aud : {
name : 'Australian Dollar',
value : 1
},
usd : {
name : 'United States Dollar',
value : 1.05
},
eur : {
name : 'Euros',
value : 0.8
},
gbp : {
name : 'British Pounds',
value : 0.67
}
}
for (var c in currency) {
var num = href.match(/\d+/), // Simple regex, maybe too simple...
conv = Math.ceil(currency[c].value * num),
url = href.replace(num, conv);
items += '<li>' +
'<a href="' + url + '">' +
currency[c].name + ' (' + c.toUpperCase() + ')' +
'</a>' +
'</li>';
}
$('.tour').replaceWith('<div><ul>' + items + '</ul></div>');
$(document).ready(function() {
var ref = $('.tour').attr('href');
function G(t) {return ref.replace(7838, t=='eur'?'8914':t=='usd'?'8062':t=='gbp'?'8907':'7838');}
$('.tour').replaceWith('<div class="currency"><p>Price & Bookings</p><ul class="currencydd" style="display:none"><li>Australian Dollar (AUD)</li><li>United States Dollar (USD)</li><li>British Pounds (GBP)</li><li>Euros (EUR)</li></ul></div>');
$('.currency').hover(function () {
$('.currencydd').slideToggle("fast");
});
});​
FIDDLE

Categories