I am receiving a string from another application that contains various pieces of information. The items are always in the same order, but the length of variable information can change. Each item is separated by an underscore and prefixed by a letter and colon.
Example:
A:12345678_B:5482945_C:20220911_D:20230402_E:3.94
Ideally, I want to break it down so that (in Coldfusion) I can end up with a series of variable that I would set as the values of A,B,C,D and E above.
Does anyone know any easy way to do this?
Thanks!
I think #Will is missing one small part of your requirement, which is
I can end up with a series of variable[s] that I would set as the values of A,B,C,D and E above"
To me this demonstrates more what you want to achieve:
raw = "A:12345678_B:5482945_C:20220911_D:20230402_E:3.94"
asArray = raw.listToArray("_")
asStruct = asArray.reduce((struct, kvAsString) => {
var key = kvAsString.listFirst(":")
var value = kvAsString.listRest(":")
struct[key] = value
return struct
}, {})
writeDump(asStruct)
(runnable # trycf.com: https://trycf.com/gist/e84aea475957e27b5dea2643e7c207ad/acf2021?theme=monokai)
Whilst this does not create "a series of variables" it does separate out the key from the value, and from there you can append that to whatever scope you need the variables in (eg: variables.append(asStruct))
In future please:
show us what you've already tried
give us the full intended result, don't just describe it.
Basically: always include code when you ask questions.
Gives you an array of the items. If you're handy with Regular Expressions, this could be even simpler. This is Lucee compatible. Adobe CFML didn't like the var commands outside of a function.
<cfscript>
var aNewItems = [];
var sString = "A:12345678_B:5482945_C:20220911_D:20230402_E:3.94";
var aItems = listToArray(sString, "_");
for( var sLetter in aItems){
aNewItems.append(listFirst(sLetter, ":"));
}
writeDump(aNewItems);
</cfscript>
Here's an Adobe CFML version that worked on TryCF.com:
<cfscript>
local.aNewItems = [];
local.sString = "A:12345678_B:5482945_C:20220911_D:20230402_E:3.94";
local.aItems = listToArray(local.sString, "_");
for( local.sLetter in aItems){
local.aNewItems.append(listFirst(local.sLetter, ":"));
}
writeDump(local.aNewItems);
</cfscript>
And just for fun, here is a list function answer:
<cfset TheString = 'A:12345678_B:5482945_C:20220911_D:20230402_E:3.94'>
<cfoutput>
<cfloop list = #TheString# index = "NameValue" delimiters = "_">
Variable #ListFirst(NameValue, ":")# = #ListLast(NameValue, ":")# <br>
</cfloop>
</cfoutput>
Run code here ==> https://trycf.com/gist/34321917c06643de1d3c25b611243466/acf2021?theme=monokai
Related
First time posting here. I'm an experienced coding, but it's been a long time since I've done any, and I'm starting back up with App Script, a new language for me. I'm trying to do some basic stuff with text found within cells in a Google sheets. I've gotten it to work well enough, but I think my code can be simplified and improved if I learn a little bit more about working with text strings in App Script.
This is a very simplified version of my function. My real function finds the page numbers given in a citation in one cell, and puts just those page numbers in another cell. For the purposes of this question, I've simplified it to retrieve the text from the current cell, remove the first blank space in the text, count the numbers at the beginning of the text, and then write just those numbers into the current cell. It does what it is supposed to do, and what I need it to do, but I have so many questions! Thank you!!
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive(); var
currentCell = spreadsheet.getCurrentCell().activate();
var style = SpreadsheetApp.newTextStyle().setForegroundColor('#000000').build();
var textString = currentCell.getRichTextValue().getText();
var count = 0;
var char = textString.substring(count,count+1);
textString = textString.replace(" ","");
while(char<10)
{
count = count+1;
char = textString.substring(count,count+1);
}
var numbers = textString.substring(0,count);
currentCell.setRichTextValue(SpreadsheetApp.newRichTextValue().setText(numbers)
.setTextStyle(1, count, style).build());
};
In retrieving my textString, is there a way to do it without using "getRichTextValue()"?
In writing the new text (numbers), is there a way to do that without using "setRichTextValue()"? And to do it without specifying the style?
In my while loop, I use char<10. This works, but I'm not sure why. char is a one character string, right? The character is a number, but I am thinking I shouldn't be able to compare with a number because it's a string? Also, it actually lets blank spaces through as well, so I know something is wrong. What can I do instead?
How can I get the replace function to remove ALL the blank spaces in my textString?
Here is a modified version of your script using Regex.
The reason your code char<10 works is it is comparing the ASCII value of the character with A being 10 and 0 to 9 being ASCII value 0 to 9.
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive();
var currentCell = spreadsheet.getCurrentCell(); // returns a range, no need to activate
var textString = currentCell.getValue();
// use reges to remove all blank spaced
textString = textString.replace(/\s/g,"");
// use regex to get the first string of digits
// match returns an array so we need the first element of the array
var numbers = textString.match(/\d+/)[0];
currentCell.setValue(numbers)
}
Reference
Range.getValue()
Range.setValue()
Regex tester
I have this string: https://2352353252142dsbxcs35#github.com/happy.git
I want to get result: https://github.com/happy.git (without random string after second / and after # but without #).
Now I have something like this:
var s = 'https://2352353252142dsbxcs35#github.com/happy.git';
var d = s.substring(s.indexOf('/')+2, s.indexOf('#')+1;
s = s.replace(d, "");
it works, but I know it's an ugly solution.
What is the most efficient and more universal solution?
Try this:
const indexOfAtSign: number = receivedMessage.indexOf('#')+1
const httpsString: string = 'https://'
const trimmedString: string = s.slice(indexOfAtSign)
const requiredURL: string = httpsString.concat(trimmedString)
// Print this value of requiredURL wherever you want.
So here what my code does is, it gets position of # and removes everything before it along with the sign itself. Then using the slice() function, we are left with the remaining part which I named as trimmedString. Now I have pre-defined the `https string, anf we just need to merge them now. Done :-)
I had tried this out in my telegram bot and here's how it works:
I am wondering is there any way to replace this type of value in string
https://farm5.staticflickr.com/4796/39790122335_bdc207b259_o.jpg https://farm5.staticflickr.com/4776/39790122225_c8e96339fa.jpg
What i want is that replace the right side of URL and just show the left side there is little space between them.
You can do that in many different ways, using many different languages.
For example, this is how you can do it with JavaScript
var str = 'https://farm5.staticflickr.com/4796/39790122335_bdc207b259_o.jpg https://farm5.staticflickr.com/4776/39790122225_c8e96339fa.jpg'
str = str.split(' ')
str = str[0]
it can be easily done using the split function.
First assign the url to a Variable
Python
theurl = 'https://farm5.staticflickr.com/4796/39790122335_bdc207b259_o.jpg https://farm5.staticflickr.com/4776/39790122225_c8e96339fa.jpg'
each_url = theurl.split()
now your new variable each url is a list of objects containing all the URLS
i.e each_url = ['https://farm5.staticflickr.com/4796/39790122335_bdc207b259_o.jpg ', 'https://farm5.staticflickr.com/4776/39790122225_c8e96339fa.jpg']
the Split function works in pretty different Programming Languages
though in some like Javascript you might have to specify split as split(' ')
showing you are splitting by spaces
I have a string ="/show/search/All.aspx?Att=A1". How to get the last value after the 'Att=' in efficient way ?
You could do a split on the '=' character.
Example (in C#):
string line = "/show/search/All.aspx?Att=A1";
string[] parts = line.Split('=');
//parts[1] contains A1;
Hope this helps
If you're only dealing with this one URL then both of the other answers would work fine. I would consider using the HttpUtility.ParseQueryString method and just pull out the item you want by key.
Whatever an
efficient way
is...
Try this:
var str = "/show/search/All.aspx?Att=A1";
var searchString = "Att=";
var answer = str.Substring(str.IndexOf(searchString) + searchString.Length);
I am currently working on a project that dynamically displays DB content into table.
To edit the table contents i am want to use the dynamically created "string"+id value.
Is there any way to retrieve the appended int value from the whole string in javaScript?
Any suggestions would be appreciative...
Thanks!!!
If you know that the string part is only going to consist of letters or non-numeric characters, you could use a regular expression:
var str = "something123"
var id = str.replace(/^[^\d]+/i, "");
If it can consist of numbers as well, then things get complicated unless you can ensure that string always ends with a non-numeric character. In which case, you can do something like this:
var str = "something123"
var id = str.match(/\d+$/) ? str.match(/\d+$/)[0] : "";
(''+string.match(/\d+/) || '')
Explanation: match all digits in the variable string, and make a string from it (''+).
If there is no match, it would return null, but thanks to || '', it will always be a string.
You might try using the regex:
/\d+$/
to retrieve the appended number