I have generated random number. So i want to add some specific places to special characters
As a example - nuzmo2b2yhougkpntd5srif0fdami12_f6gyve0acaddzmt_rbz0iwlizmioiwdmlj
This is the how to genarate random numbers.
let randomkey = [...Array(64)].map(() => Math.random().toString(36)[2]).join('')
console.log(randomkey)
As well as i tried to use splice but it doesn't work
let updatedkey = randomkey.splice(20 , 0 , "_")
This says splice is not a function!
.splice is not a method of string (MDN doc), so to use that, you should convert it to array of character using .split(''), then do .splice, then convert back to string using .join('')
let randomkey = [...Array(64)].map(() => Math.random().toString(36)[2]).join('')
console.log(randomkey)
let updatedkey = randomkey.split('')
updatedkey.splice(20, 0, "_")
updatedkey = updatedkey.join('')
console.log(updatedkey)
You can use JavaScript String slice() method:
let updatedkey = randomkey.slice(0, 20) + "_" + randomkey.slice(20);
Related
I am very new to JavaScript and still learning the fundamentals. I was completing a JavaScript challenge were i needed to square every number eg. 881 become 64641. My code is below which i am happy with but I have managed to get myself confused by overthinking.
When i do numArray[i] * numArray[i] as they are both strings does JavaScript automatically convert to a number in order for the numbers to square themselves. Did it turn it into a number - square the number - then turn back into a string again. Which is why i have to do Number(squareArray.join(''));
The reason i ask is I know that if you do string * number it turns to a number, i would if something similar happens. If I am wrong please can someone explain so I can understand.
let numArray = num.toString(); //turn number to a string
let squareArray = []; // create an array to save the new values of the string
for (let i = 0; i < numArray.length; i++) { // iterate through the string
squareArray[i] = numArray[i] * numArray[i]; // save the square of the number to the array
}
return Number(squareArray.join('')); // turn the array into a string and then into a number}
Few observations :
As you want to make a square of a number, why converting those into a string ? Keep it in number form.
As you want each square number element should concat beside each other. You can achieve that only by joining via Array.join('').
Suggestion : Use Array.map() to get square of each number.
Working Demo :
let numArray = [1,2,3,4,5];
const squareArray = numArray.map(item => item * item);
console.log(Number(squareArray.join('')));
Concise one-liner solution
const squareEveryNum = (num) => +Array.from(`${num}`, v => v * v).join("")
Array.from() creates a new shallow-copied Array instance from an iterable or array-like object. e.g Array.from("123") OR Array.from([2,4,5})
Second argument of Array.from() takes callback function to be called on each element of array.
Array.from('223', v => v * v) // [4,4,9]
.join() returns string by concatenating all elements of the array.
+ converts string to number.
Links Array.from(),
Array.join()
References don't have to be [numbers][question].
asd
I have this array:
Array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23]
I want all the values that start with "_" and are followed by 10 random characters.
So the return in this instance would be
Array = ["_B07TLNWCSV","_A674598385","_U8965H456NV"]
How would I do this in Javascript?
UPDATE
Say If I want to get all the elements on a webpage that follow the same rule,
On a webpage the element is like so:
<tr id="_B07TLNWCSV">data</tr>
how would I get all table row elements that follow the rule "_(10 RANDOM CHARS)"
I understand that querySelectorAll which get all the elements that follow the rule but I can't get it working.
Use Array.filter(), filtering words that start with _ and have a 11 chars length ( _ + 10 chars )
const array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23"];
const result = array.filter(word => word.startsWith('_') && word.length === 11);
console.log(result);
Here is a simple code that you might looking for.
Hope my code would be useful!
const array=["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23", "_123456789123"];
let newArray=[];
array.forEach(function(word){
if(word.length==11&&word[0]=="_") newArray.push(word);
});
console.log(newArray);
You just need to use filter() along with hardcoded index [0] and string length 11.
const array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23"];
const result = array.filter((f) => { return f[0] === '_' && f.length === 11 });
console.log(result);
You can use the filter() method and a regular expression for this:
var array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23"];
var filteredArray = array.filter(function(elem) {
return elem.match(/^_.{10}$/);
});
console.log(filteredArray);
Explanation of the regular expression:
^_ => the string must start with a _.
.{10} => then we must have ten characters (. means any character)
$ => end of string, i.e. the string must stop there, we can't have any more characters.
Edit: Regarding your question update, the simplest way to target these elements is to add a common class name to all of them, say:
<tr id="_B07TLNWCSV" class="data">data</tr>
<tr id="_B07TLNWDSA" class="data">data</tr>
<tr id="_B07TLNWCXB" class="data">data</tr>
And then use getElementsByClassName("data") to retrieve the elements.
I have such a string "Categ=All&Search=Jucs&Kin=LUU".How to get an array of values from this line [All,Jucs,LUU].
Here is an example
let x = /(\b\w+)$|(\b\w+)\b&/g;
let y = "Categories=All&Search=Filus";
console.log(y.match(x));
but I wanted no character &.
Since this looks like a URL query string, you can treat it as one and parse the data without needing a regex.
let query = "Categ=All&Search=Jucs&Kin=LUU",
parser = new URLSearchParams(query),
values = [];
parser.forEach(function(v, k){
values.push(v);
});
console.log(values);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Note: This may not work in IE, if that's something you care about.
Loop through all matches and take only the first group, ignoring the =
let x = /=([^&]+)/g;
let y = "Categories=All&Search=Filus";
let match;
while (match = x.exec(y)) {
console.log(match[1]);
}
To achieve expected result, use below option of using split and filter with index to separate Keys and values
1. Use split([^A-Za-z0-9]) to split string based on any special character other letters and numbers
2. Use Filter and index to get even or odd elements of array for keys and values
var str1 = "Categ=All&Search=Jucs&Kin=LUU";
function splitter(str, index){
return str.split(/[^A-Za-z0-9]/).filter((v,i)=>i%2=== index);
}
console.log(splitter(str1, 0)) //["Categ", "Search", "Kin"]
console.log(splitter(str1, 1))//["All", "Jucs", "LUU"]
codepen - https://codepen.io/nagasai/pen/yWMYwz?editors=1010
In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)
When I utilise the slice method like so:
"Hello".slice(0,-1);
The result I get will be "Hell". Then if I run through that again using the same code, I will get "Hel".
Is there a way that I can extract and store into a variable the actual character that was sliced off, in this case "H" or on the second run "e", and not just the remainder of the string?
You could just use a second .slice() on the original string.
For example, where "Hello".slice(0,-1); returns all but the last character, "Hello".slice(-1) returns only the last character.
var input = "Hello";
var removed = input.slice(-1); // "o"
var remaining = input.slice(0, -1); // "Hell"
I don't think there's a more generic solution than that, because .slice() also lets you extract the middle of a string, in which case you'd need two extra calls to get the two parts being removed.
Demo:
var input = "Hello";
var allRemoved = [];
var removed;
while (input != "") {
allRemoved.push(removed = input.slice(-1));
input = input.slice(0, -1);
console.log("'" + removed + "' removed, leaving '" + input + "'");
}
console.log("Removed: " + allRemoved.join(", "));
Alternatively, if you only care about removing characters one at a time, you could forget about .slice() and instead convert the string to an array and use .shift() or .pop() to remove the character at the beginning or end respectively:
var input = "Hello";
var inArr = input.split("");
while (inArr.length > 0) {
console.log(inArr.pop());
}
This might not be the most efficient way to do this but you can turn yout string as an array with .split, then use .splice to remove certain elements ( letters ) and store them as a variable. Finally you turn your variable of removed letters back to a string using .join
let name = 'David'
let arrayname = name.split('')
let chosenLetters = arrayname.splice(0,2)
let finalLetters = chosenLetters.join('')
console.log(finalLetters) //should output Da
For split and join I recommend you leave the argument as (''). For .splice you can find in the docs for js how to select specific letters. In my example I am saying "Start at index 0 and cut the first 2 elements". Splice has many other ways to select an index so I recommend you read the docs.
In one line of code it can be generalized to :
let name = 'David'
let finalLetters = name.split('').splice(0,2).join('')
console.log(finalLetters) //should output Da