Using JavaScript I want to take a string like this var hashStr = 'modal-123456' and assign the string left of the - to a variable and the string right of the - to another variable.
If the string does not contain a - then ignore it.
How can I best achieve this?
var hashStr = location.hash.replace('#', '');
// hashStr now === 'modal-123456'
var firstHalf = // modal
var secondHalf = // '123456'
You can use split API.
var hashStr = 'modal-123456'
var splitStr = hashStr.split('-');
console.log(splitStr[0])
console.log(splitStr[1])
Just use split.
var hashStr = 'modal-123456';
var [firstHalf, secondHalf] = hashStr.split("-");
console.log("first half:", firstHalf);
console.log("second half:", secondHalf);
Simply
var hashStr = location.hash.replace('#', '');
var firstHalf = hashStr.split("-")[0];
var secondHalf = hashStr.split("-")[1];
or
var hashStr = location.hash.replace('#', '').split("-");
var firstHalf = hashStr[0];
var secondHalf = hashStr[1];
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.
I have a string var with following:
var str = getDataValue();
//str value is in this format = "aVal,bVal,cVal,dVal,eVal"
Note that the value is separated by , respectively, and the val is not fixed / hardcoded.
How do I replace only the bVal everytime?
EDIT
If you use string as the regex, escape the string to prevent malicious attacks:
RegExp.escape = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
new RegExp(RegExp.escape(string));
var str = "aVal,bVal,cVal,dVal,eVal";
var rgx = 'bVal';
var x = 'replacement';
var res = str.replace(rgx, x);
console.log(res);
Try this
var targetValue = 'bVal';
var replaceValue = 'yourValue';
str = str.replace(targetValue , replaceValue);
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);
I have string like this:-
var src=url("http://localhost:200/assets/images/eyecatcher/6/black6.png)"
And now I want to get image name i.e black6.png and folder name 6.
I know there is substr function I can use but the file name and folder name will be dynamic like
orange12.png and 12 etc.
How I can get these values? Please help me.
Thanks
You can use split method for this:
var src = "http://localhost:200/assets/images/eyecatcher/6/black6.png";
var parsed = src.split( '/' );
console.log( parsed[ parsed.length - 1 ] ); // black6.png
console.log( parsed[ parsed.length - 2 ] ); // 6
console.log( parsed[ parsed.length - 3 ] ); // eyecatcher
etc.
If the base URL is always the same you could do
var url = "http://localhost:200/assets/images/eyecatcher/6/black6.png";
var bits = url.replace("http://localhost:200/assets/images/eyecatcher/", "").split("/");
var folder = bits[0], // 6
file = bits[1]; // black6.png
If your string is:
var src="http://localhost:200/assets/images/eyecatcher/6/black6.png"
Use the following:
var parts = src.split('/');
var img = parts.pop(); //black6.png
var flder = parts.pop(); //6
var sflder = parts.pop(); //eveatcher
You may try like this:
var str = myString.split('/');
var answer = str[str.length - 1];
var answer1 = str[str.length - 2];
var answer2 = str[str.length - 3];
var img_name = src.split('/')[7];
var folder_name = src.split('/')[6];
Using split & slice, Say like bellow
var src = "http://localhost:200/assets/images/eyecatcher/6/black6.png";
var arr = src.split('/').slice(-2) //returns ["6", "black6.png"]
arr[0] //folderName
arr[1] //filename
var str = "http://MachineName:200/assets/images/eyecatcher/6/black6.png";
var newStr = str.split("/");
ubound = newStr.length;
fileName = newStr[ubound-1];