Split strings into multiple fields based on special characters and newline - Javascript - javascript

I have a profile field where the data comes in the below format for each user profile.
User1 could have his profile field populated as below while user2 could have just one role/id/company listed in their profile.
RoleA : 123456 - company1 \n
RoleB : 234567 - company2 \n
RoleC : 891011
I am supposed to split the roles for each user into 1 field separated by commas and the id/company into another field separated by comma.
For the above data, the output should look like-
Role field - RoleA, RoleB, RoleC
ID/Company field - 123456-company1, 234567-company2.
This has to be done in JavaScript. Any suggestion is appreciated.
Thanks!

What you should do is something similar to below:
function splitProfile(profile, roleList, idCompanyList) {
var splitProfileString = profile.split(" : ");
roleList.push(splitProfileString[0]);
var splitIdCompanyString = splitProfileString[1].split(" - ");
// check if there is a company for `id`
if(splitIdCompanyString[1]) {
idCompanyList.push(splitIdCompanyString[0] + "-" + splitIdCompanyString[1].replace(" \n", ""));
}
}
var roleIdCompanyList = [
"RoleA : 123456 - company1 \n",
"RoleB : 234567 - company2 \n",
"RoleC : 891011"
];
var roleList = [];
var idCompanyList = [];
roleIdCompanyList.forEach(function(roleIdCompany) {
splitProfile(roleIdCompany, roleList, idCompanyList);
});
console.log(roleList.join(", ")); // RoleA, RoleB, RoleC
console.log(idCompanyList.join(", ")); // 123456-company1, 234567-company2
I tried to think that the input and the output are exactly similar to the ones you provided in the question. In any case, I hope you get the idea of what I am trying to do here.

Related

Javascript string - search substring if else replace

I'd like to have on an ecommerce product page the simple "in stock" or "out of stock" message, but the ERP solution that I've to use only permit to retrive from its db the number of items currentrly in stock.
I can only use JS, so I'm thinking to a small function that will search for the string I have, extract only the number, do an if/else in order to replace a trigger id with the proper content.
here the content of the function:
var strAval = strAval.search (/\<div id\=\"\#avail\" class\=\"hidden\"\>/ + /\d+/ + /<\/div>/);
var strAval2 = strAval.substring (32,-6);
if (strAval2 > 0) {
var str = document.getElementById("#in-stock").innerHTML;
var res = str.replace("#in-stock","IN STOCK");
document.getElementById("#in-stock").innerHTML = res;
}
else {
var str = document.getElementById("#in-stock").innerHTML;
var res = str.replace("#in-stock","OUT OF STOCK");
document.getElementById("#in-stock").innerHTML = res;
}
the string that I've into the html is:
<div id="#avail" class="hidden">329</div>
where "329" is an example - this number is variable from 1 to 4 digits [ 0 - 12 - 329 - 2654 ]
There's something wrong, but I don't know what.
I'm learning JS, so I'm really new to it.
Thanks to all.

Get String value between two strings through 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'/>

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).

Help parsing string (City, State Zip) with JavaScript

I've got a string with the following format:
City, State ZIP
I'd like to get City and State from this string.
How can I do that with JavaScript? edit: note that he doesn't mention he already has the zip code when he gets here, if that helps you in your solution ~~ drachenstern
var address = "San Francisco, CA 94129";
function parseAddress(address) {
// Make sure the address is a string.
if (typeof address !== "string") throw "Address is not a string.";
// Trim the address.
address = address.trim();
// Make an object to contain the data.
var returned = {};
// Find the comma.
var comma = address.indexOf(',');
// Pull out the city.
returned.city = address.slice(0, comma);
// Get everything after the city.
var after = address.substring(comma + 2); // The string after the comma, +2 so that we skip the comma and the space.
// Find the space.
var space = after.lastIndexOf(' ');
// Pull out the state.
returned.state = after.slice(0, space);
// Pull out the zip code.
returned.zip = after.substring(space + 1);
// Return the data.
return returned;
}
address = parseAddress(address);
This is probably better then using regular expressions and String.split(), as it takes into account that the state and city may have spaces.
EDIT: Bug fix: It only included the first word of multi-word state names.
And here's a minified version. :D
function parseAddress(a) {if(typeof a!=="string") throw "Address is not a string.";a=a.trim();var r={},c=a.indexOf(',');r.city=a.slice(0,c);var f=a.substring(c+2),s=f.lastIndexOf(' ');r.state=f.slice(0,s);r.zip=f.substring(s+1);return r;}
There are many ways to do this. Here's a very naive one:
var parts = "City, State ZIP".split(/\s+/); // split on whitespace
var city = parts[0].slice(0, parts[0].length - 1); // remove trailing comma
var state = parts[1];
var zip = parts[2];
Here's one that accounts for the presence of spaces in either the city or state or both:
var parts = "san fran bay, new mex state 666666".split(/\s+|,/),
partition = parts.indexOf(""),
city = parts.slice(0, partition).join(" "),
state = parts.slice(partition + 1, -1).join(" "),
zip = parts.pop();
This last one only works if you're lucky enough to be in an environment that supports destructuring assignment:
var city, statezip, state, zip, parts;
[city, statezip] = "Spaced City, New Mexico ZIP".split(/,\s*/);
parts = statezip.split(/\s+/);
zip = parts.pop();
state = parts.join(" ");
None of these perform any validation, of course.
Ok, since advising regex isn't good, here's my solution. It takes into account cities that have spaces in them, which the other responses here don't seem to do:
var str = "New York, NY 20101";
var cityAndRest = str.split(',');
var city = cityAndRest[0];
var stateAndZip = cityAndRest[1].trim().split(' ');
var state = stateAndZip[0];
var zip = stateAndZip[1];
First assumption: American addresses only.
First find out if the last 5 or the last 10 characters are numeric. A simpler test is to see if the last character is numeric. If so, it's probably got the zip code included. Then a simple test to see if the last 10 contains a space (city #####) or if the last ten include a dash (12345-6789) to figure out if it's a 5 or 5+4 zip. We'll test for a hyphen and no space. (city-du-lac 12345 captures -lac 12345)
Next, all addresses split the city and state by a comma, so we want the last comma. Find the index of the last comma, and split there. I don't know of a city that uses commas in it's name, and I'm sure not gonna let my parser burst on an unknown if I can help it. I do ignore the fact that Washington DC could also be Washington, DC. I figure edge cases are for libraries, not one off scripts.
Lastly, trim everything that remains to remove trailing or leading spaces.
function IsNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var addr = 'New York City, New York 10101';
//var addr = 'San Bernadino, CA 11111';
function getCityStateZip(addr){
var city; var state;var zip;
city = ''; state = ''; zip = '';
var addrLen = addr.length;
if ( IsNumeric( addr.substring(addrLen - 1) ) ) {
//contains a zipcode - just a sanity check
//get last 10 characters for testing easily
var lastTen = addr.substring( addrLen - 10 );
if ( lastTen.indexOf('-') > 0 && ( lastTen.indexOf(' ') == -1 ) ) {
//found a hyphen and no space (matches our complex rule for zipcodes)
zip = lastTen;
} else {
zip = addr.substring( addrLen - 5 ); //assume a basic 5 zip code
}
}
var zipLen = zip.length;
addrLen = addrLen - zipLen - 1;
addr = addr.substring(0, addrLen ); //remove the chars we just moved into zip
var lastComma = addr.lastIndexOf(',');
if ( lastComma == -1 ) {
//you have a problem, how do you want to handle it?
}
city = addr.substring(0,lastComma); //skip the comma itself, yes?
state = addr.substring(lastComma + 2);
return { 'city':city,'state': state,'zip': zip};
}
getCityStateZip(addr)
IsNumeric js function can be found here Validate decimal numbers in JavaScript - IsNumeric()
Easy way but no validation:
var addrObj={};
parseAddress("Beverly Hills, CA 90210",addrObj);
function parseAddress(address, addrObj){
var arr=address.replace(","," ").split(" ");
addrObj.zip=arr.pop();
addrObj.state=arr.pop();
addrObj.city=arr.join(" ");
}
For this type of thing you might want to use JavaScripts RegEx functions.
Here's some info:
http://www.javascriptkit.com/javatutors/re.shtml

Categories