add conditional character every i-th place in a string - javascript

I want to write a function where given an index it adds a <br> tag at every Ith index in string. If the index is a space we will insert a <br>, but if it's in the middle of a string we insert -<br>
I saw a lot of examples using a combination of regex and joins, but I wasnt sure how to do this since my join would be conditional.
For Example:
let my_string = "Here's a really really long string that I want to add breaks to at every 20th interval"
I'd like my function insert_break(my_string, 20) to return
Here's a really reall-<br>y long string that I<br> want to add breaks <br>to at every 20th interval
So far my function works at the first specified index, but I wasnt sure if I should write a loop or recursive function in order to get this to work at every index interval in the string (in the example at [20,60,40] and right now it just works at 20
Any help with the function appreciated:
insert_break = (str, index) => {
// mostly we'll need to hyphenate the new line
let breakword = "-<br>"
// but if there's a space before the index we dont
if (str[index] === " ") { breakword = "<br>" }
// I want this to run at every multiple of 20 within the string
// so I need some kind of for loop (or something recursive?)
// to add a <br> at every multiple of the index
if (index > 0) {
// this works if we only want to run this function ONCE at the index 20
//return str.substring(0, index) + breakword + str.substring(index)
let breakstring = str
for (let i = 1; i < Math.floor(str.length/index); i++) {
// 1*20, 2*20, 3*20
let idx = index*i
// this doesnt work.
// I need to add it to the new string, not write over the old one as I am here
breakstring = breakstring.substring(0, idx) + breakword + breakstring.substring(idx)
}
return breakstring
//return str.substring(0, index) + breakword + str.substring(index)
}
return breakword + str
}
Any help appreciated!

Loop over the string indexes in steps of index. Use substring() to extract each chunk of characters from the string, check its last character, and then append the appropriate form of <br>.
function insert_break(str, index) {
let result = "";
for (let i = 0; i < str.length; i += index) {
let chunk = str.substring(i, i + index);
if (chunk.endsWith(' ')) {
chunk += '<br>';
} else {
chunk += '-<br>';
}
result += chunk;
}
result = result.replace(/-?<br>$/, ''); // remove last `<br>`
return result;
}
let my_string = "Here's a really really long string that I want to add breaks to at every 20th interval";
console.log(insert_break(my_string, 20));
Indexes start at 0, not 1, so you need to use that as the initial value of i.

Related

How to retain spaces in input strings of Caesar Cipher for javascript?

This project is in javascript. I need to make sure the output retains spaces found in the string that is inputted into the function. The test I am trying to pass is calling the function for the term "hello world" with a shift of 13 letters. From this code, the result is "uryybjbeyq" and "uryyb jbeyq" is expected. I have identified I need an if statement which I have included already, but not sure what command I should include before the continue keyword that will insert the space needed. I am a beginner and this is only my 3rd project so any assistance would be appreciated. Please find the corresponding code below.
function caesarCypher(string, num){
// line below is the encrypted string we will return from the function
const letters = 'abcdefghijklmnopqrstuvwxyz';
let encryptStr = ""
// loop through every character in the inputted string
for(let i = 0; i < string.length; i++){
// line below will look up index of char in alphabet
let char = string[i];
/* if statement below is attempting to identify the space in the original string and then add a command that will add a space to the encrypted string then continue to work through the rest of the input */
if (char === " ") {
//need something to put on this line to insert space;
continue;
}
let index = letters.indexOf(char);
// index + num below will give us the letter 7 spots over
let newIndex = index + num;
// if statement below makes the function loop back around
if (newIndex > 26) {
newIndex = newIndex - 26;
}
let newChar = letters[newIndex];
encryptStr += newChar;
}
return encryptStr;
}
/* invoke the function with these parameters to pass the test-- expected result is 'uryyb jbeyq'*/
caesarCypher("hello world", 13)
You can add the white space like this:
encryptStr += " ";
I tried your code and I ran into an error... All letters were the same. Here is how I did it:
function caesarCypher(string, num){
let encryptStr = "";
for(let i = 0; i < string.length; i++){
let char = string[i];
if (char === " ") {
encryptStr += " "; //This adds a white space.
continue;
}
// If you want to keep the case of a letter, skip the
// "toLowerCase()" and extend the condition below.
let asciiCode = string.toLowerCase().charCodeAt(i) + num;
if(asciiCode > 122) {
asciiCode -= 26;
}
encryptStr += String.fromCharCode(asciiCode);
}
return encryptStr;
}

Replace specific elements (unique or duplicates) from a string in JS

My code automatically search the string for /d+d/d+ elements (roll dices) and adds random number suffixes and stores them as elements in an array.
I want to create a new string with the new modified elements of my array.
(I don't want to split string in Array, replace the same elements with the other array in a brand new one and then join it to a string. I need to modify it and save it in a new string)
Example:
String changes through user input so if i have:
str = ' I roll 1d3 and 2d4+3 and 1d3 also 1d8 and 1d8 dice ';
then mydice(str) finds all dice names and produces a new array like that:
array = [ "1d3:[2]=2" , "2d4:[1,2]+3=6" , "1d3:[1]=1", "1d8:[7]=7", "1d8:[5]=5"] ;
Desired Output:
str = ' I roll 1d3:[2]=2 and 2d4:[1,2]+3=6 and 1d3:[1]=1 also 1d8:[7]=7 and 1d8:[5]=5 ';
Using only the two items you provide as input (the string and the array with ndn=(n) kind of words), you can proceed as follows:
let str = ' I roll 1d3 and 2d4+3 and 1d3 also 1d8 and 1d8 dice ';
let array = [ "1d3:[2]=2" , "2d4:[1,2]+3=6" , "1d3:[1]=1", "1d8:[7]=7", "1d8:[5]=5"];
let i = 0;
for (let item of array) {
let find = item.replace(/:.*\]|=.*/g, "");
i = str.indexOf(find, i);
str = str.slice(0, i) + item + str.slice(i + find.length);
i += item.length;
}
console.log(str);
It is assumed that the array is well-formed, i.e. that indeed those items were derived correctly from the string and all the string-parts before the equal sign (like "1d3") occur in the string.
Note that strings are immutable, so you cannot really mutate a string. The only way is to create a new string and assign it back to the same variable. But that is not mutation; that is assignment of a new string.
If I understood your requirements, I think your solution is overcomplicated. I'd suggest something like this:
const roll = dice => {
const [num, max] = dice.split('d');
let r = 0;
for (let i = 0; i < num; i++) {
r += Math.floor(Math.random() * max) + 1;
}
return r;
}
let output = input = 'I roll 1d3 and 2d4 and 1d3 also 1d8 and 1d8 dice';
const matches = input.match(/\d+d\d+/g);
const rolls = matches.map(dice => `${dice}=(${roll(dice)})`);
rolls.forEach(roll => {
const [dice] = roll.split('=');
output = output.replace(new RegExp(` ${dice} `), ` ${roll} `);
});
console.log('IN:', input)
console.log('OUT:', output);

How to search for an index of specific word with an index of specific character

Say for example I have the words below
THIS TEXT IS A SAMPLE TEXT
I am given character index 7.
Then I have to return index 1 when I split the sentence into words which is the index of the word that contains the index of character not 5 which matches the word that composes the index of character exactly but not the correct index where character lies.
basically I am trying to return the correct word index of where character lies (when split into words) with character index (when split with characters)
I thought I would reconstruct the word with something like below to find the word at the character
let curString = 'find a word from here';
let initialPositin = 5
let position = initialPositin
let stringBuilder = '';
while(position > -1 && curString.charAt(position) !== ' '){
console.log('run 1')
console.log(position);
stringBuilder = curString.charAt(position) + stringBuilder;
position --;
}
console.log(stringBuilder)
position = initialPositin + 1;
while(position < curString.length && curString.charAt(position) !== ' '){
console.log('run 2')
stringBuilder += curString.charAt(position);
position ++;
}
console.log(stringBuilder);
Then split the sentence into words then find all the index of the word that contains the word that I have constructed. Then go through all the found words and reconstruct the previous words to see if the index of the target character in the reconstruction matches the character position given.
It doesn't really feel efficient. Does anyone have better suggestions?
I prefer javascript but I can try to translate any other language myself
I think you could just count spaces that occurs before given index, something like
let curString = 'find a word from here';
let givenIndex = 9;
let spaceIndex = 0;
for (var i = 0; i < curString.length; i++) {
if(curString.charAt(i) == ' ') {
if (i < givenIndex) {
spaceIndex++;
} else {
// found what we need
console.log(spaceIndex);
}
}
}
Maybe you could build a function that returns the position of all spaces.
Then you can see where the character index fits in that list of space positions.
text = "THIS TEXT IS A SAMPLE TEXT"
indexes = []
current_word = 0
for i in range(0, len(text)):
if text[i] == ' ':
current_word += 1 # After a ' ' character, we passed a word
else:
indexes.append(current_word) # current character belongs to current word
You can build indexes array for once with this piece of code(written in Python3) then you can use it for every indice. If you want to count ' ' characters in indexes array as well, you can simple add them in for loop(in if statement).
I ended up using below code
let content = 'THIS IS A SAMPLE SENTENCE';
let target = 13;
let spaceCount = 0;
let index = 0;
while(index < target) {
if (content.charAt(index) === ' ') {
spaceCount++;
}
index++;
}
let splitContent = content.split(' ');
splitContent[spaceCount] = '#' + value
console.log(splitContent.join(' '))
Worked very nicely
Just like the answer from #miradham this function counts the spaces before the given index, but with builtin functions to count character occurrences.
function wordIndexOfCharacterIndexInString(index, string) {
const stringUpToCharacter = string.slice(0, index)
return (stringUpToCharacter.match(/ /g) || []).length
}
console.log(wordIndexOfCharacterIndexInString(7, "THIS TEXT IS A SAMPLE TEXT"))

Insert random string into each instance of whitespace

I'm trying to insert a randomly selected string into each instance of whitespace within another string.
var boom = 'hey there buddy roe';
var space = ' ';
var words = ['cool','rad','tubular','woah', 'noice'];
var random_words = words[Math.floor(Math.random()*words.length)];
for(var i=0; i<boom.length; i++) {
boom.split(' ').join(space + random_words + space);
}
Output comes to:
=> 'hey woah there woah buddy woah roe'
I am randomly selecting an item from the array, but it uses the same word for each instance of whitespace. I want a word randomly generated each time the loop encounters whitespace.
What I want is more like:
=> 'hey cool there noice buddy tubular roe'
Thanks for taking a look.
(This is beta for a Boomhauer twitter bot, excuse the variables / strings 😅)
Maybe you can use regex instead however, you are not seeing the result you desire because you are randomly selecting one word and then replacing all occurrences of a space with it.
The regular expression below replaces occurrences of a space with a dynamic value returned by a callback. You could compare this callback to your for-loop but instead, it's iterating over the spaces found and by doing so you can replace each occurrence with a 'unique' random word.
const boom = 'hey there buddy roe';
const words = ['cool', 'rad', 'tubular', 'woah', 'noice'];
const random = () => Math.floor(Math.random() * words.length);
let replace = boom.replace(/ /g, () => ` ${words[random()]} `);
console.log(replace);
The problem is, that random_words is set to a single word.
Try this instead:
var boom = 'hey there buddy roe';
var words = ['cool','rad','tubular','woah', 'noice'];
boom.replace(/ /g, (space)=> space + words[Math.floor(Math.random()*words.length)] + space);
To get the effect you desire, you need to do the word selecting inside the loop, not outside of it.
for(var i=0; i<boom.length; i++) {
// get a new number every loop
var random_words = words[Math.floor(Math.random()*words.length)];
boom.split(' ').join(space + random_words + space);
}
What is wrong with OP's code: random_words is initialized once only, with a random word. Intention there is, however, to select random word for every whitespace encountered instead.
You can either go with:
for(var i=0; i<boom.length; i++) {
boom.split(' ').join(space + words[Math.floor(Math.random()*words.length)] + space);
}
... or make random_words a function that returns a random word, then call it in your 'boom' loop. With every call, a new word selection will occur.
You need to recalculate the random word on each loop. Right now you have picked out a single random word, stored it in the random_words variable, and you reuse it each time. You could modify your code like this:
var boom = 'hey there buddy roe';
var space = ' ';
var words = ['cool','rad','tubular','woah', 'noice'];
function getRandomWord() {
return words[Math.floor(Math.random()*words.length)];
}
// Uses the same because the value given to join is not recalculated each time:
console.log(boom.split(' ').join(space + getRandomWord() + space));
// You could do this with a standard for loop:
let result = "";
let split = boom.split(' ')
for(var i=0; i<split.length; i++) {
result += split[i] + space;
if (i === split.length - 1) break;
result += getRandomWord() + space;
}
console.log(result);
// Or you can use a reduce:
let otherResult = boom.split(' ').reduce((res, word, index, split) => {
if (index === split.length - 1) return res + space + word;
return res + space + word + space + getRandomWord();
});
console.log(otherResult)

converting a string to numbers Javascript

I've starting messing up with javascript lately and stumbled upon some problem.
I'm allowing my user to insert a series of numbers separated by white-spaces into a text field. I am trying to read the string from the text field and store the numbers in an array. However, I have those 0's added unwillingly. I went thru my code over and over, yet I cannot find whats wrong.
the code:
function get_input(str)
{
var arr = [];
var elem=0;
for(var i=0,j=1; i<str.length ;i++,j++)
{
if (j == str.length) {elem += str[i];
arr.push(elem);
return arr;}
else if (str[j]== " ")
{
elem *=10;
elem +=str[i];
arr.push(elem);
elem=0;
i++;
j++
}
else
{
elem *=10;
elem += str[i];
}
}
return arr;
}
e.g for an input:123 45 6
the output is : 10203*405*06*
I put the * only to see the elements in the array,
Help will be much appreciated.
function get_input(str){
var a = str.split(' ');
for(var i = 0; i < a.length; i++){
a[i] = parseFloat(a[i]);
}
return a;
}
Break-down:
Using the split method, we're populating an array with the strings separated by the ' ' (space) delimiter.
We then cycle through the array in order to parse the results into Numbers. If this isn't needed (i.e you're happy with the digits being represented as Strings) then you don't need that extra step.
We then return the array.

Categories