Take random letters out from a string - javascript

I want to remove 3 RANDOM letters from a string.
I can use something like substr() or slice() function but it won't let me take the random letters out.
Here is the demo of what I have right now.
http://jsfiddle.net/euuhyfr4/
Any help would be appreciated!

var str = "hello world";
for(var i = 0; i < 3; i++) {
str = removeRandomLetter(str);
}
alert(str);
function removeRandomLetter(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos)+str.substring(pos+1);
}
If you want to replace 3 random charc with other random chars, you can use 3 times this function:
function substitute(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos) + getRandomLetter() + str.substring(pos+1);
}
function getRandomLetter() {
var letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var pos = Math.floor(Math.random()*letters.length);
return letters.charAt(pos);
}

You can split the string to an array, splice random items, and join back to a string:
var arr = str.split('');
for(var i=0; i<3; ++i)
arr.splice(Math.floor(Math.random() * arr.length), 1);
str = arr.join('');

var str = "cat123",
amountLetters = 3,
randomString = "";
for(var i=0; i < amountLetters; i++) {
randomString += str.substr(Math.floor(Math.random()*str.length), 1);
}
alert(randomString);
fiddle:
http://jsfiddle.net/euuhyfr4/7/

This answer states that
It is faster to slice the string twice [...] than using a split followed by a join [...]
Therefore, while Oriol's answer works perfectly fine, I believe a faster implementation would be:
function removeRandom(str, amount)
{
for(var i = 0; i < amount; i++)
{
var max = str.length - 1;
var pos = Math.round(Math.random() * max);
str = str.slice(0, pos) + str.slice(pos + 1);
}
return str;
}
See also this fiddle.

you can shuffle characters in your string then remove first 3 characters
var str = 'congratulations';
String.prototype.removeItems = function (num) {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("").substring(num);
}
alert(str.removeItems(3));

You can use split method without any args.
This would return all chars as a array.
Then you can use any randomiser function as described in Generating random whole numbers in JavaScript in a specific range? , then use that position to get the character at that position.
Have a look # my implementation here
var str = "cat123";
var strArray = str.split("");
function getRandomizer(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
alert("Total length " + strArray.length);
var nrand = getRandomizer(1, strArray.length);
alert("Randon number between range 1 - length of string " + nrand);
alert("Character # random position " + strArray[nrand]);
Code # here https://jsfiddle.net/1ryjedq6/

Related

I have a string with counts and alphabets in ordered manner i have to print the alphabets according to their count

var input = `2
6
z2k1o2
6
m2v1p2`
var newInput = input.split("\n")
//console.log(newInput.length)
var input_arr = input.trim().split("\n")
var n = Number(input_arr[0])
//console.log(input_arr)
for (var i = 1; i < input_arr.length; i = i + 2) {
var length = Number(input_arr[i])
var string = input_arr[i + 1].trim()
}
//console.log(string)
var newstring = string
//console.log(newstring)
var alpha = []
var num = []
for (i = 1; i < string.length; i += 2) {
num.push(string[i])
}
var newnum = num.map(Number)
//console.log(newnum)
for (i = 0; i < string.length; i += 2) {
alpha.push(string[i])
}
var newalpha = (alpha)
//console.log(newalpha)
var answer = []
for (i = 0; i < newnum.length; i++) {
for (j = 0; j < newnum[i]; j++) {
answer.push(newalpha[i])
}
}
console.log(answer.join(""))
Here I'm getting only one output can you please explain why And do you like share any other approach for this problem.
This is the input z2k1o2 and the output should be zzkoo
The input will follow this patter of alphabets ans counts..
I'd do this with a regular expression that captures pairs of (character, number) and uses the function-replacement mode of .replace() to generate the replacement string.
> "a2b1c2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
"aabcc"
>"pos2es2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
"possess"
Here's where you're running into your error:
for (var i = 1; i < input_arr.length; i = i + 2) {
var length = Number(input_arr[i])
var string = input_arr[i + 1].trim()
}
You're going through the entire input array and saving each of the lengths and strings, but you're overwriting the length and the string each time you read it - only the last length and last string are saved, and so only the last length and last string are processed / printed.

How can I remove the last emoji of a group of emojis in javascript?

Let's say I have this 3 emojis in a string: πŸ˜€πŸŽƒπŸ‘ͺ
There are not any spaces or any other character except emojis in the string.
How can I remove the last emoji in javascript?
The answer below doesn't use any special package and safely removes the last emoji
function safeEmojiBackspace(str)
{
let initialRealCount = fancyCount(str);
while(str.length > 0 && fancyCount(str) !== initialRealCount - 1)
{
str = str.substring(0,str.length - 1);
}
return str;
}
function fancyCount(str){
const joiner = "\u{200D}";
const split = str.split(joiner);
let count = 0;
for(const s of split){
//removing the variation selectors
const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length;
count += num;
}
//assuming the joiners are used appropriately
return count / split.length;
}
Sample usage
let str = "somethingπŸ˜€πŸŽƒπŸ‘ͺ";
str = safeEmojiBackspace(str);//"somethingπŸ˜€πŸŽƒ"
You can do this. It will always remove the last emoji.
function removeEmoji() {
var emoStringArray = document.getElementById('emoji').innerHTML;
var lastIndex = emoStringArray.lastIndexOf(" ");
var stripedEmoStringArray = emoStringArray.substring(0, lastIndex);
document.getElementById('emoji').innerHTML = stripedEmoStringArray;
}
<p id="emoji">
πŸ˜€ πŸŽƒ πŸ‘ͺ
</p>
<button onclick="removeEmoji()">Remove</button>
I hope this is what you want.
var emoString = "πŸ˜€ πŸŽƒ πŸ‘ͺ";
emoString = emoString.slice(0, -2);
However, this would work only if you have 3 emojis in total. Hence to achieve a generalised solution, you can use the underscore functions split() and javascript function join() :
var emoString = "πŸ˜€ πŸŽƒ πŸ‘ͺ";
emoString = _.rest(emoString.split(' ')).join(' ')
Hope this will solve your issue.
Ok, here is how I solved it:
function deleteEmoji(emojiStr) {
let emojisArray = emojiStr.match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g);
emojisArray = emojisArray.splice(0, emojisArray.length - 1);
return emojisArray.join("");
}
let emojitext = "πŸ˜€πŸŽƒπŸ‘ͺ";
console.log(deleteEmoji(emojitext));
I was actually surprised that unicode in this day an age is still not fully supported in browsers. I assume a lot of this is down to windows and it's version of UTF-16.
The OP I believe has found his own solution to the original problem, but I thought there has to be a more generic solution to surrogate pair unicode characters.
Anyway, so my solution is convert the text into a UTF-32 array, these can then be manipulated must easier, using slice etc.
After you have done what you want to the array, just convert back.
Below is an example.
Some of the code I got from -> Is it possible to convert a string containing "high" unicode chars to an array consisting of dec values derived from utf-32 ("real") codes?
and http://speakingjs.com/es5/ch24.html
function decodeUnicode(str) {
const r = [];
let i = 0;
while(i < str.length) {
let chr = str.charCodeAt(i++);
if(chr >= 0xD800 && chr <= 0xDBFF) {
var low = str.charCodeAt(i++);
r.push(0x10000 +
((chr - 0xD800) << 10) | (low - 0xDC00));
} else {
r.push(chr);
}
}
return r;
}
function toUTF16(codePoint) {
const TEN_BITS = parseInt('1111111111', 2);
if (codePoint <= 0xFFFF) { return codePoint; }
codePoint -= 0x10000;
const leadingSurrogate = 0xD800 | (codePoint >> 10);
const trailingSurrogate = 0xDC00 | (codePoint & TEN_BITS);
return String.fromCharCode(leadingSurrogate) +
String.fromCharCode(trailingSurrogate);
}
function encodeUnicode(data) {
return data.reduce((a, v) => {
a += toUTF16(v);
return a;
},"");
}
var unicode = decodeUnicode("πŸ˜€πŸŽƒπŸ‘ͺ");
for (let l = 0; l < unicode.length; l ++)
console.log(encodeUnicode(
unicode.slice(0, l ? -l : unicode.length)));
console.log("pick some random ones");
let str = "";
for (let l = 0; l < 20; l ++) {
let rnd = Math.trunc(Math.random()*unicode.length);
str += encodeUnicode(unicode.slice(rnd,rnd+1));
}
console.log(str);

Perform a merge on two strings

I'm trying to build a collaborative doc editor and implement operational transformation. Imagine we have a string that is manipulated simultaneously by 2 users. They can only add characters, not remove them. We want to incorporate both of their changes.
The original string is: catspider
The first user does this: cat<span id>spider</span>
The second user does this: c<span id>atspi</span>der
I'm trying to write a function that will produce: c<span id>at<span id>spi</span>der</span>
The function I've written is close, but it produces c<span id>at<span i</span>d>spider</span> codepen here
String.prototype.splice = function(start, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start);
};
function merge(saved, working, requested) {
if (!saved || !working || !requested) {
return false;
}
var diffSavedWorking = createDiff(working, saved);
var diffRequestedWorking = createDiff(working, requested);
var newStr = working;
for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {
//splice does an insert `before` -- we will assume that the saved document characters
//should always appear before the requested document characters in this merger operation
//so we first insert requested and then saved, which means that the final string will have the
//original characters first.
if (diffRequestedWorking[i]) {
newStr = newStr.splice(i, diffRequestedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffRequestedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
if (diffSavedWorking[i]) {
newStr = newStr.splice(i, diffSavedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffSavedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
}
return newStr;
}
//arr1 should be the shorter array.
//returns inserted characters at their
//insertion index.
function createDiff(arr1, arr2) {
var diff = [];
var j = 0;
for (var i = 0; i < arr1.length; i++) {
diff[i] = "";
while (arr2[j] !== arr1[i]) {
diff[i] += arr2[j];
j++;
}
j++;
}
var remainder = arr2.substr(j);
if (remainder) diff[i] = remainder;
return diff;
}
function insertNatX(arr, length, pos) {
for (var j = 0; j < length; j++) {
arr.splice(pos, 0, "");
}
}
var saved = 'cat<span id>spider</span>';
var working = 'catspider';
var requested = 'c<span id>atspi</span>der';
console.log(merge(saved, working, requested));
Would appreciate any thoughts on a better / simpler way to achieve this.

How to repeat characters in a string in javascript by using slice function?

Can anyone shed light on how to frame a javascript function with two parameters: string and character, and only by using the slice method, return the number of times "a" appears in "lava"?
without slice method
var fruits= "lavaaagg";
var count=0;
for(var i=0;i<fruits.length;i++){
if(fruits[i]!='a')
count++;
}
console.log(fruits.length-count);
I'm not sure why you need the slice method. The slice method isn't for searching substrings (or characters in your case), it extracts a substring.
This should work fine:
function howManyCharInStr(str, char) {
return str.split(char).length - 1;
}
Step-by-step explanation:
str.split(char)
Creates an array of str substrings, using char as a separator. For example:
'fooXbazXbar'.split('X')
// Evaluates to ['foo', 'baz', 'bar']
'lorem ipsum dolor'.split('m')
// Evaluates to ['lore', ' ipsu', ' dolor']
Notice how the array returned has a length of n+1 where n is the number of separators there were. So use
str.split(char).length - 1;
to get the desired result.
For getting number of charecters count
<script type="text/javascript">
function FindResults() {
var firstvariable= document.getElementById('v1');
var secondvariable = document.getElementById('v2');
var rslt = GetCharecterCount(firstvariable, secondvariable );
}
function GetCharecterCount(var yourstring,var charecter){
var matchesCount = yourstring.split(charecter).length - 1;
}
</script>
using slice method
var arr = yourstring.split(charecter);
for( var i = 0, len = arr.length; i < len; i++ ) {
var idx = yourstring.indexOf( arr[i] );
arr[i] = pos = (pos + idx);
str = str.slice(idx);
}
var x= arr.length-1;
example http://jsfiddle.net/rWJ5x/2/
Using slice method
function logic(str,char){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str.slice(i,i+1) == char){
count++;
}
}
return count;
};
console.log( "count : " + logic("lava","a") );
repeat last character of sting n number of times..
function modifyLast(str, n) {
var newstr = str.slice(-1)
var newlaststr = newstr.repeat(n-1)
var concatstring = str.concat(newlaststr);
return concatstring;
}
//modifyLast();
console.log(modifyLast("Hellodsdsds", 3))

How can I make my output appear all on one line with no spaces?

I have a simple Javascript problem that I'm working on, where the point is to...
Take an input, like 123
Separate the input as single digits, then square those single digits, thus getting 149.
Display that "149" (in this case) as an output.
I don't know how to display it as 149. I can only show it as
1
4
9
Sure, I might try adding it to an array then for looping the results... something tells me that this is the slow solution, and that there is a faster one. Here's my code.
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
console.log(newnum);
}
}
squareDigits(123);
Create empty array outside of the loop
Add squares of the each digit in the array
Join the array after loop finishes
function squareDigits(num) {
num = '' + num;
var len = num.length;
var squares = []; // Define empty array
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
squares.push(Math.pow(digit, 2)); // Push the square of the digit at the end of array
}
return squares.join(''); // Join the array elements with empty string as glue
}
var squares = squareDigits(123);
console.log(squares);
document.write(squares);
By string concatenation
Declare a empty string before the for loop
Concatenate the square of the digit to the string by first casting the number to string
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum = ''; // Decalare variable with Empty string
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum += '' + Math.pow(digit, 2); // Cast the square to string and then concatenate to the string
}
return newnum; // Return the string
}
var squares = squareDigits(123);
document.write(squares);
Try utilizing String.prototype.split() , Array.prototype.map() , Array.prototype.join()
function squareDigits(num) {
return String(num).split("")
.map(function(n) {
return Math.pow(n, 2);
}).join("");
}
console.log(squareDigits(123));
What about this?
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
var digits = '';
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
digits += '' + newnum
}
console.log(digits);
}
try process.stdout.write, as in
process.stdout.write(newnum);

Categories

Resources