I have data two sets of data as follows:
"One.Two.Three.Four"
"One.Two.Three.1.Four"
The first three parts are fixed and the remaining can extend to as many as possible.
I am trying to build an object where I want to split and combine whatever is present after three into an object.
var split = samplestr.split('.');
var finalarray = [];
if(split.length>4)
{
finalarray[0] = split[0];
finalarray[1] = split[1];
finalarray[2] = split[2];
finalarray[3] = split[3]+"."split[4];
}
I need to generalise this such that even if the string is of the form
"One.Two.Three.1.2.3.Four"
finalarray[3] = 1.2.3.Four;
Any hints on generalising this?
With Array#shift and Array#join.
var split = samplestr.split('.');
var finalarray = [];
if(split.length > 4) {
finalarray[0] = split.shift();
finalarray[1] = split.shift();
finalarray[2] = split.shift();
finalarray[3] = split.join(".");
}
simply replace
finalarray[3] = split[3]+"."split[4];
with
finalarray[3] = split.slice(3).join(".");
Split the string, slice the first part and append the join'ed second part:
console.info=function(x){document.write('<pre>'+JSON.stringify(x,0,3)+'</pre>')}
//--
var str = "One.Two.Three.Four.More.Stuff";
var s = str.split('.');
var result = s.slice(0, 3).concat(s.slice(3).join('.'));
console.info(result);
Related
Example:
let somestr = '11>22>33>44';
let someSpecificWord = '22';
I want to get a result like this
'11>22'
How to cut or use method for this?
You may use String#substring with String#lastIndexOf:
let somestr = '11>22>33>44';
let someSpecificWord = '22';
console.log(somestr.substring(0, somestr.lastIndexOf(someSpecificWord) + someSpecificWord.length));
In case u want all of the numbers included in result.
var str = '11>22>33>44';
var splitstr = str.split('>');
var strarray =[];
for(var i=0; i<splitstr.length-1;i++){
strarray[i] = splitstr[i]+'>'+splitstr[i+1];
$("span").append(strarray[i]+"<br />");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="span"></span>
You can also split() the string to array and then find the indexOf() the work, then join() using > to get the final result. For better code management, create a reusable function.
function cutWord(str, word){
var splitStr = str.split('>');
return splitStr.slice(0,splitStr.lastIndexOf(someSpecificWord)+1).join('>');
}
var somestr = '11>22>33>44';
var someSpecificWord = '22';
console.log(cutWord(somestr, someSpecificWord));
someSpecificWord = '33';
console.log(cutWord(somestr, someSpecificWord));
someSpecificWord = '11';
console.log(cutWord(somestr, someSpecificWord));
Instead of "var instance = ..." adding the two values it concatenates them. Can anyone suggest what I need to fix?
I'm trying to add "var startingEmail" value and "var k".
Thank you for your help!
var startingEmail = sheet.getRange("C2").getDisplayValue();
var numEmails = sheet.getRange("E2").getDisplayValue();
var max = numEmails;
for (var k = 0; k<max; ++k){
var threads = GmailApp.getInboxThreads(startingEmail,max)[k]; //get max 50 threads starting at most recent thread
var messages = threads.getMessages()[0];
var sndr;
var rcpnt;
var srAry = [];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var sndrLower = sndr.toLowerCase;
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
var rcpntLower = rcpnt.toLowerCase;
var cc = messages.getCc().replace(/^.+<([^>]+)>$/, "$1");
var ccLower = cc.toLowerCase;
//srAry.push(sndr);
//srAry.push(rcpnt);
//srAry.push(cc);
var isIn = joinAddr.search(sndr || rcpnt);
if(isIn == -1){
var instance = k;
I can't see the example in your code but it sounds like you can just wrap Number() around your variable and it will perform the type conversion so the code will perform the math instead of concatenating as strings.
Is there by any chance a built-in javascript function that parses:
var string = '[2,1,-4]';
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
to
var array = [2,1,-4];
var multiArray = [[-3,2,-1],[2,-3,2],[1,-1,3]];
or do I have to write a custom function for this?
Assuming your correct your multiString to the correct format
(ie. '[[-3,2,-1],[2,-3,2],[1,-1,3]]')
Then yes.
array = JSON.parse(string);
multiArray = JSON.parse(multiString);
For completeness, you can use eval:
var s = '[1,2,3]';
var a = eval(s);
however if the string is valid JSON, then as Niet suggested, JSON.parse is a much better solution.
If you want to do this on your own, it can be done using substring and split. A possible solution could look like this:
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
var string = '[2,1,-4]';
function parse(input) {
var s = input;
// remove leading [ and trailing ] if present
if (input[0] == "[") {
s = input.substring(0, input.length);
}
if (input[input.length] == "]") {
s = s.substring(input.length-1, 1);
}
// create an arrray, splitting on every ,
var items = s.split(",");
return items;
}
// items is now an array holding 2,-1,4
var items = parse(string);
You can then split the bigger string into smaller chunks and apply the function to each part using array.map:
function parseAOfA(input) {
var s = input.substring(0, input.length).substring(input.length-1, 1);
s = s.substring(0, s.length).substring(s.length-1, 1);
s = s.split("][");
var items = s.map(parse);
return items;
}
var items = parseAOfA(multiString);
I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.
How can I retrieve multiple indexes from multiple instances of a string search?
var str = "food";
var index1 = str.search("o"); // 1
var index2 = str.search("o"); // ?
Thanks much,
Wen
I think the best way to do this for strings of non-trivial length is the RegExp.exec() function:
var str = "Foooooooood!",
re = /o/g,
match;
while (match = re.exec(str)) {
console.log(match.index); // logs 1 through 9
}
You can use second parameter of indexOf method to achieve what you want:
var str = "food",
index1 = str.indexOf("o"),
index2 = str.indexOf("o", index1+1);