javascript Function string.slice - javascript

I'm trying to do this following javascript exercise here:
Create a function called mixUp. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long.
and here's my code:
var mixUP = function(a, b) {
var sliceA = a.slice(0,2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0,2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUp(apple, pear);
Could anyone please help me out here coz it's not working for me. Thanks heaps!

The way I approached it was:
function mixUp(stringA, stringB) {
var sliceA = stringA.slice(0,2),
sliceB = stringB.slice(0,2);
return (sliceB + stringA.substring(2) + " " + sliceA +
stringB.substring(2));
}
Which gives you the desired output

If you define mixUP call it, not mixUp last p is uppercase.
When you use strings, you need to add quotes around them:
var mixUp = function (a, b) {
var sliceA = a.slice(0, 2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0, 2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUp('apple', 'pear');
OUTPUT
apar peple

Typo's:
mixUp(apple, pear);
should be:
mixUP('apple', 'pear');
^ ^ ^ ^ ^
You called mixUp instead of mixUP, and both apple and pear should be strings (Unless they are variables already)
That'll give you the desired result:
var mixUP = function(a, b) {
var sliceA = a.slice(0,2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0,2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUP('apple', 'pear');

Either change the function calling or the function definition to same name as you have taken different names for both.
var mixUP = function(a, b) {
var sliceA = a.slice(0,2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0,2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUP("apple", "pear"); // apar peple

Related

javascript split String at quotation marks // Json.parse gives undefined object

I have a string with this value:
[{"email":"SharePoint.Admin_SA.external#test.net","id":"i:0#.w|opmain\\xespsa","label":"Admin_SA, SharePoint","title":"SharePoint Projektteam SP","type":"User","value":"i:0#.w|opmain\\xespsa"}]
The strings all have the same format. It can also be
[{"email":"SharePoint.Admin#test.net","id":"i:0#.w|opmain\\xespec","label":"Admin, SharePoint","title":"SharePoint Projektteam SP","type":"User","value":"i:0#.w|opmain\\xespec"}]
But I need a "global" approach, so that it always splits it at label. For example, splitting the first one should only output Admin_SA, SharePoint.
How can one achieve this?
I tried the following, but it didn't give me the result I wanted:
var test = NWF$("#" + varRequestor).val();
var array = test.split(':');
var a = array[0];
var b = array[1];
var c = array[2];
var d = array[3];
var e = array[4];
console.log("a: " + a);
console.log("b: " + b);
console.log("c: " + c);
console.log("d: " + d);
console.log("e: " + e);
I tried using JSON.parse as well, but it didn't work:
console.log("Requestor DispName: " + NWF$("#" + varRequestor).val());
var obj = NWF$("#" + varRequestor).val();
const test = JSON.parse(obj);
console.log("obj.label:" + obj.label);
i think, you want value corresponding to label. you can try this.
let temp = [{"email":"SharePoint.Admin_SA.external#test.net","id":"i:0#.w|opmain\\xespsa","label":"Admin_SA, SharePoint","title":"SharePoint Projektteam SP","type":"User","value":"i:0#.w|opmain\\xespsa"}];
console.log(temp[0].label);

Javascript method to convert string value

Can someone please help me to write a JS method which takes a String value like
/Content/blockDiagram/0/bundle/0/selectedBundle
/Content/blockDiagram/1/bundle/1/selectedBundle
/Content/blockDiagram/0/bundle
and convert it to
/Content/blockDiagram[1]/bundle[1]/selectedBundle
/Content/blockDiagram[2]/bundle[2]/selectedBundle
/Content/blockDiagram[1]/bundle
It is basically taking the number in the path and increment it by 1 and then changing the structure of the string.
My attempt
function setReplicantPartListOptions(list) {
list = "/" + list;
var index = list.lastIndexOf("/");
var tempString = list.substring(0, index);
var index2 = tempString.lastIndexOf("/");
var initialString = list.substring(0, index2);
var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
var lastString = list.substring(index, list.length);
list = initialString + "[" + middlevalue + "]" + lastString;
return list;
}
simple regular expression with capture group with replace
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
var next = +num + 1; // convert string to number and add one
return "[" + next + "]"; //return the new string
})
console.log(updated)
String.replace(RegExp, callback(match, contents)) is the callback version of String.replace().
In my case, the first parameter of callback function is the result/match. It takes the match and converts it to number using + operator, and then increment it by one. Finally, I add [ ] around the value and return it!
let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)

Java script written for UUID is not working in jmeter

Find below the code we have developed in java script to run in jmeter using JSR223 sampler(running as a java script). The same code worked on Jquery when developed but not posting the id while running in jmeter. the error thrown is "appid" is not defined. Could someone help debugging the issue looking at the code
vars.put("guid", "${__UUID}"); 
vars.put("appId", "ce547c40-acf9-11e6-80f5-76304dec7eb7");
var id=getAppInfo(appId, guid);
function getAppInfo(appId, guid)
{
var appInfo = null;
var appIdBytes = guidToBytes(appId);
var guidBytes = guidToBytes(guid);
var appInfoBytes = [];
for (var cnt = 0; cnt < appIdBytes.length; cnt++)
{
appInfoBytes[cnt] = appIdBytes[cnt] + guidBytes[cnt];
}
var appInfoGuidfromBytes = bytesToGuid(appInfoBytes);
return appInfoGuidfromBytes;
}
function bytesToGuid(guidBytes) {
var x = guidBytes;
var result = "";
var bytes = x.slice(0, 4).reverse().concat(x.slice(4, 6).reverse()).concat(x.slice(6, 8).reverse()).concat(x.slice(8));
var y = bytes.map(function (item) { return ('00' + item.toString(16)).substr(-2, 2) });
var byteArray = y;
for (var cnt = 0; cnt < byteArray.length; cnt++) {
if (cnt === 4 || cnt === 6 || cnt === 8 || cnt === 10)
result = result + "-" + byteArray[cnt];
else
result = result + byteArray[cnt];
}
return result;
}
function guidToBytes(guid) {
var bytes = [];
guid.split('-').map(function (number, index) {
var bytesInChar = index < 3 ? number.match(/.{1,2}/g).reverse() : number.match(/.{1,2}/g);
bytesInChar.map(function (byte) { bytes.push(parseInt(byte, 16)); });
});
return bytes;
}
// Create the Randon Number. It will call from NewGuid function.
function getRandomNumber() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
// Creating GUID eg. "cbe26df8-2b01-4377-9ae8-1d023ccd5171"
// getRandomNumber returns 4 digit Alphanumeric number and we are going to concatenating this with "-" symbol and third number starts with "-4" and substring the random number and concatenate the string and return.
function newGuid() {
return (getRandomNumber() + getRandomNumber() + "-" + getRandomNumber() + "-4" + getRandomNumber().substr(0, 3) + "-" + getRandomNumber() + "-" + getRandomNumber() + getRandomNumber() + getRandomNumber()).toLowerCase();
};
You shouldn't call JMeter's function inside JSR223 script.
Instead, add it to Parameters field as ${__UUID}
and then use it using args:
vars.put("guid", args[0]);
args - the parameters as a String array (split on whitespace)

Cannot read properly "split"

I have this piece of code in javascript:
var i = 0;
var j = 0;
while (allTextLines.length) {
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
if (i == 0) {
alert(temp);
i++;
}
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
var y = line[3];
var z = line[5];
var g = line[7];
lines[j] = (x + ", " + z + ", " + g);
j++;
}
And it's happening something really weird. When i==0, it alerts temp and its split. After that I'm getting:
Uncaught TypeError: Cannot read property 'split' of undefined
If I remove the if, I will have this error right on the start. But if I do something like this:
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
alert(temp);
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
It has no problem splitting (also the alert shows that it has been correctly split). The only problem is that I will have to click "ok" 5600 times. I don't understand what the hell is going on and why I am having this error.
I'm splitting a CSV file with lines like this:
35105,201401,503781827,"8400258","Faro","Lagoa (Algarve)","Portugal"
and I'm trying to add an '-' in here: "8400258", so it becomes "8400-258"
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
Won't that fail when allTextLines only has one element in it, since the array is zero-based? I think you'd need to change the line[x] param to 0:
var temp = line[0].split('');
Might I suggest a different approach?
var line = allTextLines.shift().split(',');
var x = line[3].replace(/^"(\d{4})(\d{3})"$/, "$1-$2");
var y = line[4];
var z = line[5];
var g = line[6];
If you can trust that the format of the data is always the same, it's much less complex to do a pattern based replace than splitting a string like an array and re-assembling it.

javascript string remove a character at position X and add to start

If I have a string and a number:
var str='Thisisabigstring';
var numb=7;
I'm trying to remove the character at position 'numb' from the string and then put it at the beginning of the string.
Trying for output like:
'aThisisbigstring';
How can I do this with javascript/jquery?
var str = "Thisisabigstring";
var numb=7;
var c = str.charAt(numb);
str = c + str.substr(0, numb) + str.substr(numb + 1);
quick and dirty :)
var b = str.charAt(numb - 1) + str.substring(0, numb - 1) + str.substring(numb);
var s = "Thisisabigstring";
var index = 7;
var x = s.charAt(index) + s.substr(0, (index - 1)) + s.substr(index + 1);
alert(x);
There is no function in javascript which do that. Try this :
String.prototype.replaceCharAt=function(index, char){return this.substr(0, index) + char + this.substr(index+char.length);}
var testStr = your_Test_string;
var CharPosition = Ur_Char_Position;
var pullOutChar = testStr.charAt(CharPosition);
testStr = pullOutChar + str.substr(0, CharPosition) + str.substr(CharPosition + 1);
Sometimes it's easier to convert a string to an Array when doing things like this:
str = str.split('');
str.unshift(str.splice(numb - 1, 1));
str = str.join('');
var x = str.substring(7,8);
str = x + str;

Categories