1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

vue.js javascript textarea 指定文字数で改行コードを挿入

Posted at

指定した文字数で改行を入れたい。
例えば、

ラーメンつけめん僕イケメン

ラーメン
つけめん
僕イケメ
ン

にする。
textarea に soft やら hard やら指定しろと書いてあるが、
してもうまく動かないのでjavascriptで整形しちゃお♪

コード

textLimit に 1行の最大文字数を設定するだけ。
あとはコピペで動く。

hoge.vue

var textLimit = 4;//ここだけ設定
var tmp = this.form.body.split("\n");

var kaigyouBody = [];


for (var key in tmp) {

    if(tmp[key] != ""){
    
        if(tmp[key].length >= textLimit){
        
            let oneSplit = tmp[key].split('');
            let oneBody = [];
        
            for (var key2 in oneSplit) {
            
            //key2 1文字目でなく、さらに textLimit の倍数の数値なら改行コードを挿入
            if(key2 != 0 && key2%textLimit == 0){
                oneBody.push("\n");
            }
        
            oneBody.push(oneSplit[key2]);
        
        }
        
            kaigyouBody.push(oneBody.join(""));
        
        } else {
            kaigyouBody.push(tmp[key]);
        }
        
    }

}


var result = kaigyouBody.join("\n");

console.log(result);

こんな感じ。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?