【发布时间】:2019-04-21 13:32:35
【问题描述】:
我有一个函数可以将字符串分成两行。它根据空格所在的位置打破字符串:
splitSentenceInHalfCC(sentence: string): [string, string] {
let middle = Math.floor(sentence.length / 2);
let before = sentence.lastIndexOf(' ', middle);
let after = sentence.indexOf(' ', middle + 1);
if (middle - before < after - middle || after === -1) {
middle = before;
} else {
middle = after;
}
let s1 = sentence.substr(0, middle);
let s2 = sentence.substr(middle + 1);
return [s1, s2];
}
我现在要做的是添加一个 if 语句,如果有零个空格,它将在前 15 个字符之后将字符串分成两行,比方说。我怎样才能做到这一点?我对此很陌生,所以不知道如何进行。谢谢你。
Example #1 input: This is a Store name and it is detailed.
Example #1 output: This is a Store name
and it is detailed.
Example #2 input: Thisisjustalongstorenamewithnospaces.
Example #2 output: Thisisjustalongstorename
withnospaces.
【问题讨论】:
-
@CertainPerformance 我刚刚在我想要实现的输入和输出底部的示例中更新了我的问题。
-
谢谢,现在已经很清楚了,虽然整个字符串
Thisisjustalongstorenamewithnospaces.有36个字符长,所以如果你想在前35个字符之后拆分,会不会导致["Thisisjustalongstorenamewithnospaces", "."]?跨度> -
@CertainPerformance 这只是一个例子。为此,假设我们将其拆分为 15 个字符。
标签: javascript string function conditional