Home > database >  add conditional character every i-th place in a string
add conditional character every i-th place in a string

Time:10-11

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!

CodePudding user response:

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