in javascript, what is the easiest way to convert this string
798205486e954fa880a0b366e6725f71
to GUID format like this
79820548-6e95-4fa8-80a0-b366e6725f71
this is the messy way I do it :) im looking for the cleanest way
var employeeId = shift.employee.id.substring(0, 8) + "-" + shift.employee.id.substring(8, 12)
+ "-" + shift.employee.id.substring(12, 16) + "-" + shift.employee.id.substring(16, 20) + "-" + shift.employee.id.substring(20, 32);
Cleanest way?
Shortest:
var txt = shift.employee.id;
txt.replace(/([0-z]{8})([0-z]{4})([0-z]{4})([0-z]{4})([0-z]{12})/,"$1-$2-$3-$4-$5");
//"79820548-6e95-4fa8-80a0-b366e6725f71"
or if you don't care about the acceptable characters, it can be be even shorter (and cleaner):
txt.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5"); //boom!
Some don't like using regex for everything, but I liked it.
I did it in string manipulation
var str = "798205486e954fa880a0b366e6725f71";
var parts = [];
parts.push(str.slice(0,8));
parts.push(str.slice(8,12));
parts.push(str.slice(12,16));
parts.push(str.slice(16,20));
parts.push(str.slice(20,32));
var GUID = parts.join('-');
console.log(GUID) // prints expected GUID
I did it this way because I don't like inserting characters between strings. If there is any problem tell me.
Or you could use a for loop like bellow
var str = "798205486e954fa880a0b366e6725f71";
var lengths = [8,4,4,4,12];
var parts = [];
var range = 0;
for (var i = 0; i < lengths.length; i++) {
parts.push(str.slice(range,range+lengths[i]));
range += lengths[i];
};
var GUID = parts.join('-');
console.log(GUID);
You could use an regular expression:
var rxGetGuidGroups = /(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/,
employeeId = shift.employee.id.replace(rxGetGuidGroups, '$1-$2-$3-$4-$5');
jsFiddle
Try this function, It will return string in GUID format
function getGuid(str){
return str.slice(0,8)+"-"+str.slice(8,12)+"-"+str.slice(12,16)+
"-"+str.slice(16,20)+"-"+str.slice(20,str.length+1)
}
Or you would try-
var guid = (function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function () {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
Where
Your new guid be like-
var newGuid= guid();
newGuid returns- 7d4b3ef0-b5bb-5c42-2a02-80a4371babf8
Related
I have the following cypress command function created,
Cypress.Commands.add("gen_date", () => {
var now_dt = new Date(Date.now());
var dte =
("0" + now_dt.getDate()).slice(-2) +
("0" + now_dt.getHours()).slice(-2) +
("0" + now_dt.getMinutes()).slice(-2) +
("0" + now_dt.getSeconds()).slice(-2) +
("00" + now_dt.getMilliseconds()).slice(-3);
return dte;
});
I call this command in the following test file ,
it("see if test string generated in input", () => {
let o = cy.gen_date();
cy.get("input[id=\"inputid\"]")
.as("inputinput")
.type(o)
.type("{enter}");
I expect o to be a string, but instead in cypress tests I get the error, cy.type() can only accept string or number and you passed in [object, Object]
Could someone point me in the right dirction
Cypress custom commands return a Chainable which passes the result forward to the next linked command, so you can access it by nesting
cy.gen_date().then(dt => {
cy.get("input[id=\"inputid\"]")
.as("inputinput")
.type(dt)
.type("{enter}");
})
or use plain JS function instead of a custom command
const gen_date = () => {
var now_dt = new Date(Date.now());
var dte = ("0" + now_dt.getDate()).slice(-2) +
("0" + now_dt.getHours()).slice(-2) +
("0" + now_dt.getMinutes()).slice(-2) +
("0" + now_dt.getSeconds()).slice(-2) +
("00" + now_dt.getMilliseconds()).slice(-3);
return dte;
};
let o = gen_date();
cy.get("input[id=\"inputid\"]")
.as("inputinput")
.type(o)
.type("{enter}");
Adding the function globally:
in /cypress/support/index.js
Cypress.gen_date = () => {
var now_dt = new Date(Date.now());
var dte = ("0" + now_dt.getDate()).slice(-2) +
("0" + now_dt.getHours()).slice(-2) +
("0" + now_dt.getMinutes()).slice(-2) +
("0" + now_dt.getSeconds()).slice(-2) +
("00" + now_dt.getMilliseconds()).slice(-3);
return dte;
};
in the test
let o = Cypress.gen_date();
I'm currently using this to format an input text to have "-" after two characters and it replaces characters that are not "a-f" or "0-9" with "".
var macAddress = document.getElementById("macInput");
function formatMAC(e) {
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.target.value.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + '-' + '$2');
}
e.target.value = str.slice(0, 17);
};
macAddress.addEventListener("keyup", formatMAC, false);
I want it to also detect if the user writes ":" and replace it with "-", so it becomes impossible to write ":". Not sure how to accomplish this.
Easy. .split().join()
var macAddress = document.getElementById("macInput");
function formatMAC(e) {
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.target.value.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + '-' + '$2');
}
e.target.value = str.slice(0, 17).split(':').join('');
};
macAddress.addEventListener("keyup", formatMAC, false);
on calling pushValue() function each time generating unique id by calling getGUID() after that assigning to objectJson.id and pushing to array but in console.log() it displays all object with same unique id.
<button onclick="pushValue()">
Click
</button>
<p id='displayjson'>
</p>
<script>
var arrayJson = [];
var objectJson = {
name: "New Widget",
sizeX: 4,
sizeY: 1,
lib: 'fsf',
id:""
};
var pushValue = function(){
objectJson.id = getGUID();
arrayJson.push(objectJson);
document.getElementById("displayjson").innerText = JSON.stringify(arrayJson);
console.log(arrayJson);
}
function getGUID() {
//DOCS : -http://guid.us/GUID/JavaScript
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
var guid = ('svg_id_' + S4() + S4() + "_" + S4() + "_4" + S4().substr(0, 3) + "_" + S4() + "_" + S4() + S4() + S4()).toLowerCase();
return guid;
}
</script>
click on this link https://jsfiddle.net/Akkikumar77/noLhzbwr/
It's happening because you push the objectJson reference to the array. So if you change the object, it changes in every occurence. To avoid this, you need to clone the object before pushing to the array with Object.assign()
arrayJson.push(Object.assign({}, objectJson));
Here is the updated fiddle.
You are changing same object each time, so you are pushing that object only (a reference) not newly created object. Make a simple factory function and you're good to go. Or clone the object.
var arrayJson = [];
var createObject = function(){
return{
name: "New Widget",
sizeX: 4,
sizeY: 1,
lib: 'fsf',
id: getGUID()
}
}
var pushValue = function(){
arrayJson.push(createObject());
document.getElementById("displayjson").innerText = JSON.stringify(arrayJson);
console.log(objectJson);
}
This is as a result of mutation.
Each time you call objectJSON.id = getGUID() you change the id value of the original objectJSON.
To stop referencing the original objectJSON object you use the concat method which makes a deep copy of it as opposed to using the push method.
Like this
arrayJson.concat([objectJSON]);
instead of
arrayJson.push(objectJson);
You were changing the object, not duplicating it or creating a new one. Here's one way to do it using most of your code:
Fiddle here
<button onclick="pushValue()">
Click
</button>
<p id='displayjson'>
</p>
<script>
var arrayJson = [];
var objectJson = {
name: "New Widget",
sizeX: 4,
sizeY: 1,
lib: 'fsf',
id:"",
};
function CreateObject(name, id){
this.name = name;
this.sizeX = 4;
this.sizeY = 1;
this.lib = 'fsf';
this.id = id;
}
var pushValue = function(){
var myNewObject = new CreateObject('someName', getGUID());
arrayJson.push(myNewObject);
document.getElementById("displayjson").innerText = JSON.stringify(arrayJson);
console.log(objectJson);
}
function getGUID() {
//DOCS : -http://guid.us/GUID/JavaScript
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
var guid = ('svg_id_' + S4() + S4() + "_" + S4() + "_4" + S4().substr(0, 3) + "_" + S4() + "_" + S4() + S4() + S4()).toLowerCase();
return guid;
}
</script>
I found the follow problem, I have that code it is inside a loop.
window.setInterval(function() {
requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + getFunc + "/?access_token=" + accessToken;
What I need, the variable deviceID need a increment of variable B example:
requestURL = "https://api.spark.io/v1/devices/" + deviceID[B] + "/" + getFunc + "/?access_token=" + accessToken;
So deviceID[B] that B is 1 or 2 or 3, because I have variables with the name deviceID1, deviceID2, deviceID3.
Can you help me?
It's a bad idea to concatenate a variable name, use an array instead:
var myArr = [deviceID1, deviceID2, deviceID3];
for (var i = 0; i < myArr.length; i++) {
var requestURL = "https://api.spark.io/v1/devices/" + myArr[i] + "/" + getFunc + "/?access_token=" + accessToken;
}
The above is a simple example on how you could use an array.
I'm trying to create unique ids, and I can't see why it's not working. Guess I'm blind staring at the same code for too long. I would appreciate if someone could help me! :)
function laggtill(cool, namnVara) {
var date = new Date();
var id = "" + date.getHours() + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
var vara = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
var span = document.createElement("span");
span.innerText = namnVara;
vara.appendChild(checkBox);
vara.appendChild(span);
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if (!namnVara || namnVara == "" || namnVara == " ") {
return false;
}
};
Stole this from jQuery UI. It's as simple as it's effective:
// at initialization
var uuid = 0;
// and when you need a unique id
var uniqueId = 'uid-' + (++uuid);
No need for complicated stuff like getting dates etc. unique != complicated
And to set the ID to an element:
var element = document.createElement('div');
element.id = uniqueId;
And if you want to use it more often in a script, you could create a function:
var uuid = 0; // put it in the 'global scope'
var uniqueId = function() {
return 'uid-' + (++uuid);
};
alert(uniqueId()); // uid-1
alert(uniqueId()); // uid-2
if you really want to keep the date.
var d = new Date();
var id = "" + d.getHours() + d.getMinutes() + d.getSeconds()+ d.getMilliseconds();
add some stuff to generate guid to :
var guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
http://jsfiddle.net/mz4qpg1L/1/
if you want to append id to youre control, i like appending html directly :
vara.appendChild('<span id=' + id + ' ></span>');
this way you can put any attribute you want.