javascript 如何在javascript中的一定数量的字符后在空格处拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16246031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:53:31  来源:igfitidea点击:

How do I split a string at a space after a certain number of characters in javascript?

javascriptjqueryregexstringweb

提问by muzzledBYbrass

So I have a nice long string that I need to split in Javascript at a space following a certain amount of characters. For instance, if I have

所以我有一个很好的长字符串,我需要在 Javascript 中在一定数量的字符后面的空格处拆分。例如,如果我有

"You is a dog and I am a cat."

“你是狗,我是猫。”

and I want it to split after 10 characters but at the next space... so rather than splitting dog up I want the next space to be the split point.

并且我希望它在 10 个字符后拆分,但在下一个空格处......所以我希望下一个空格成为拆分点,而不是拆分狗。

I hope I wrote that clearly, its a bit awkward to explain.

我希望我写的清楚,解释起来有点尴尬。

EDIT: I need to store all of this into an array. So splitting the string up as I described, but storing it into an array which I can iterate through. Sorry for the confusion- like I said, a bit odd to describe.

编辑:我需要将所有这些存储到一个数组中。所以按照我的描述拆分字符串,但将它存储到一个我可以迭代的数组中。抱歉造成混乱 - 就像我说的,描述起来有点奇怪。

回答by georg

Consider:

考虑:

str = "How razorback-jumping frogs can level six piqued gymnasts!"
result = str.replace(/.{10}\S*\s+/g, "$&@").split(/\s+@/)

Result:

结果:

[
 "How razorback-jumping",
 "frogs can level",
 "six piqued",
 "gymnasts!"
]

回答by Explosion Pills

.indexOfhas a fromparameter.

.indexOf有一个from参数。

str.indexOf(" ", 10);

You can get the string before and after the split, respectively, with:

您可以分别使用以下方法获取拆分前后的字符串:

str.substring(0, str.indexOf(" ", 10));
str.substring(str.indexOf(" ", 10));

回答by flavian

Is this what you are after? http://jsfiddle.net/alexflav23/j4kwL/

这是你追求的吗? http://jsfiddle.net/alexflav23/j4kwL/

var s = "You is a dog and I am a cat.";
s = s.substring(10, s.length); // Cut out the first 10 characters.
s = s.substring(s.indexOf(" ") + 1, s.length); // look for the first space and return the
// remaining string starting with the index of the space.
alert(s);

To wrap it up, String.prototype.indexOfwill return -1if the string you are looking for is not found. To make sure you don't get erroneous results, check for that before the last part. Also, the index of the space may be string.length - 1(the last character in the string is a space), in which case s.index(" ") + 1won't give you what you want.

总结一下,如果没有找到您要查找的字符串,String.prototype.indexOf将返回-1。为确保您不会得到错误的结果,请在最后一部分之前进行检查。此外,空格的索引可能是string.length - 1(字符串中的最后一个字符是空格),在这种情况下s.index(" ") + 1不会给你你想要的。

回答by Xotic750

This should do what you want, and no regexs

这应该做你想做的,没有正则表达式

var string = "You is a dog and I am a cat.",
    length = string.length,
    step = 10,
    array = [],
    i = 0,
    j;

while (i < length) {
    j = string.indexOf(" ", i + step);
    if (j === -1) {
        j = length;
    }

    array.push(string.slice(i, j));
    i = j;
}

console.log(array);

On jsfiddle

jsfiddle 上

And here is a jsperfcomparing this answer and the regex answer that you chose.

这是一个比较此答案和您选择的正则表达式答案的jsperf

Additional: if you want to trim the spaces from each block of text then change the code like so

附加:如果您想从每个文本块中修剪空格,请像这样更改代码

array.push(string.slice(i, j).trim());

回答by elclanrs

Here's a regex solution for some variety:

这是一些不同的正则表达式解决方案:

var result = [];
str.replace(/(.{10}\w+)\s(.+)/, function(_,a,b) { result.push(a,b); });

console.log(result); //=> ["You is a dog", "and I am a cat."]

回答by Mike Samuel

function breakAroundSpace(str) {
  var parts = [];
  for (var match; match = str.match(/^[\s\S]{1,10}\S*/);) {
    var prefix = match[0];
    parts.push(prefix);
    // Strip leading space.
    str = str.substring(prefix.length).replace(/^\s+/, '');
  }
  if (str) { parts.push(str); }
  return parts;
}

var str = "You is a dog and I am a cat and she is a giraffe in disguise.";
alert(JSON.stringify(breakAroundSpace(str)));

produces

产生

["You is a dog",
 "and I am a",
 "cat and she",
 "is a giraffe",
 "in disguise."]