如何在第n个空格中将长字符串拆分为两个? [英] How can I split a long string in two at the nth space?

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

问题描述

这些字符串可能是长段落,所以我不确定最好用空格分隔符分割整个字符串。我试着得到前10个单词并将它们包裹在一个范围内:

These strings may be long paragraphs, so I'm not sure it's best to split the entire string with a space delimiter. I'm trying to get, say, the first 10 words and wrap them in a span:

'< span class =easing >'+ string +'< / span>'

然后使用原始拆分的后半部分重新加入。建议以超高效的方式做到这一点?它一次最多会影响页面上的三个段落。

Then rejoin that with the second half of the original split. Suggestions on a super efficient way to do this? It would affect at most three paragraphs on the page at a time.

已编辑

这是一个踢球者 - 分裂应该发生在第9个单词之后或者在第一个句子结尾处(如果那个句子小于9个单词)。

Here's a kicker — The split should occur after the 9th word OR at the end of the first sentence (if that sentence is less than 9 words).

示例

var origString = 'Coming into the world on Elvis’ birthday with a doctor named Presley seemed fortuitous until, wielding the silvery smooth scalpel in his aged unsteady hand, the doctor sliced through the walls of my mother’s uterus and into my unborn skin. Inside the warm soothing waters of my mother’s womb, inside the silent weightlessness, I was safe. Then the prick of cold steel marked the first in a series of rude awakenings. I was scarred for life even before birth.';
var newString = '<span="easing">Coming into the world on Elvis’ birthday with a doctor</span> named Presley seemed fortuitous until, wielding the silvery smooth scalpel in his aged unsteady hand, the doctor sliced through the walls of my mother’s uterus and into my unborn skin. Inside the warm soothing waters of my mother’s womb, inside the silent weightlessness, I was safe. Then the prick of cold steel marked the first in a series of rude awakenings. I was scarred for life even before birth.';

或者用短句开头:

var origString = '"Is he okay? Tell me everything’s okay" she pleas, her desperate need to confirm my health competing with her own need for consolation.';
var newString = '<span class="easing">"Is he okay?</span> Tell me everything’s okay" she pleas, her desperate need to confirm my health competing with her own need for consolation.';


推荐答案

return string.replace(/.+?[,.?!]|.+$/, function(match, index, string){
    var words = match.split(/\s+/);
    words[ words.length<10 ? words.length-1 : 9 ] += '</span>';
    return '<span class="easing">' + words.join(" ");
});

这匹配第一句类似的东西(或整个字符串 - 除非换行符),并包装该跨度中的前10个单词。适用于您的样本输入,也适用于较小的输入。返回空字符串的空字符串,如果想要空跨度,请将正则表达式更改为 ... |。* $

This matches the first sentence-like thing (or the whole string - unless linebreaks), and wraps the first 10 words of it in that span. Works for both your sample inputs, but also on smaller ones. Returns the empty string for an empty string, change the regex to …|.*$ if you want an empty span.

这篇关于如何在第n个空格中将长字符串拆分为两个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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