仅在特定位置之间且仅当字符串中有空格时才添加换行符 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/9/25 17:48:17

我们需要编写一个函数,例如 breakString(),它接受两个参数:第一,要断开的字符串;第二,一个数字,表示字符数的阈值,达到该阈值后,我们必须重复添加换行符来代替空格。

例如 −

如果已经过了 4 个字符而没有换行符 −,则以下代码应在最近的空格处推送换行符。

const text = 'Hey can I call you by your name?';
console.log(breakString(text, 4));

预期输出 −

Hey can
I call
you by
your
name?

因此,我们将使用 for 循环进行迭代,我们将对插入‘
’已经经过的字符数进行计数,如果计数超出限制并且遇到空格,我们将在新字符串中用换行符替换它,并将计数重置为 0,否则我们将继续在新字符串中插入原始字符串字符并继续增加计数。

其完整代码为 −

示例

const text = 'Hey can I call you by your name?';
const breakString = (str, limit) => {
   let brokenString = '';
   for(let i = 0, count = 0; i < str.length; i++){
      if(count >= limit && str[i] === ' '){
         count = 0;
         brokenString += '
';       }else{          count++;          brokenString += str[i];       }    }    return brokenString; } console.log(breakString(text, 4));

输出

控制台输出将是 −

Hey can
I call
you by
your
name?

相关文章


有用资源