在JavaScript中一定数量的字符后在空格处拆分字符串 [英] Split string at space after certain number of characters in Javascript

查看:83
本文介绍了在JavaScript中一定数量的字符后在空格处拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个工具,该工具接受输入文本并将其按特定的#个字符分割成文本块.但是,我需要确保它不会将单词中间的文本分开.

I am attempting to create a tool that takes an input text and splits it into chunks of text at a certain # of characters. However, I need to make sure it does not split the text in the middle of a word.

在我的情况下,我将字符串分割为155个字符.

In my case, I am splitting the string after 155 characters.

我已经进行了大量的搜索以尝试找到一种解决方案,但是我担心它可能比我对Javascript的理解要复杂的多.我相信我只需要做出某种逻辑即可,如果分隔符位于单词中间,则分隔符会回退到要分隔的空间,但是我不确定如何写出这样的东西.

I've done quite a lot of searching to try and find a solution, but I fear it may be more complicated than my knowledge of Javascript allows me to figure out. I believe I just need to make some sort of logic that has the splitter backtrack to a space to split if it is in the middle of a word, but I am not sure how to write out such a thing.

这是我目前的javascript代码:

Here is my javascript code at the moment:

function splitText() {
    "use strict";
    var str = document.getElementById("user_input").value;
    var size = 195;
    var chunks = new Array(Math.ceil(str.length / size)),
        nChunks = chunks.length;

    var newo = 0;
    for (var i = 0, o = 0; i < nChunks; ++i, o = newo) {
          newo += size;
          chunks[i] = str.substr(o, size);
    }

    var newq = 0;
    for (var x = 0, q = 0; x < nChunks; ++x, q = newq) {
        $("#display").append("<textarea readonly>" + chunks[x] + "</textarea><br/>");
    }
}

这是我的HTML:

<body>
    <content>
        <h1>Text Splitter</h1>
        <form>
            <label>Enter a Message</label>
            <input type="text" name="message" id="user_input">
        </form>
        <form>
            <input type="button" onclick="splitText();" id="submit" value="Submit!"> <br/>
        </form>
        <label>Your split message: </label>
        <p><span id='display'></span></p>
    </content>
</body>

如果您想看一下,这是当前工作形式的代码: https://jsfiddle.net/add4s7rs/7/

Here is the code in its current working form, if you'd like to take a look: https://jsfiddle.net/add4s7rs/7/

谢谢!感谢您的协助!

推荐答案

使用regexp将字符串拆分为特定长度的块的简便方法:

A short and simple way to split a string into chunks up to a certain length using a regexp:

console.log(str.match(/.{1,154}(\s|$)/g));

一些例子:

var str = 'the quick brown fox jumps over the lazy dog';
console.log(str.match(/.{1,10}(\s|$)/g))
Array [ "the quick ", "brown fox ", "jumps over ", "the lazy ", "dog" ]
console.log(str.match(/.{1,15}(\s|$)/g))
Array [ "the quick brown ", "fox jumps over ", "the lazy dog" ]

之所以可行,是因为默认情况下,量词(在本例中为{1,154})是贪婪的,会尝试匹配尽可能多的字符.将(\s|$)放在.{1,154}之后会强制匹配终止于空白字符或字符串的结尾.因此,.{1,154}(\s|$)将最多匹配154个字符,后跟一个空白字符.然后/g修饰符使它继续匹配整个字符串.

This works because quantifiers (in this case {1,154}) are by default greedy and will attempt to match as many characters as they can. putting the (\s|$) behind the .{1,154} forces the match to terminate on a whitespace character or the end of the string. So .{1,154}(\s|$) will match up to 154 characters followed by a whitespace character. The /g modifier then makes it continue to match through the entire string.

要将其放在您的函数上下文中:

To put this in the context of your function:

function splitText() {
    "use strict";
    var str = document.getElementById("user_input").value;
    var chunks = str.match(/.{1,154}(\s|$)/g);

    chunks.forEach(function (i,x) {
        $("#display").append("<textarea readonly>" + chunks[x] + "</textarea><br/>");
    });
}

这篇关于在JavaScript中一定数量的字符后在空格处拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆