在Javascript中最近的空格处拆分文本/字符串 [英] Split text/string at closest space in Javascript

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

问题描述

我真的很挣扎如何将最接近字符串的文本拆分为第47个字符。
如何完成?

I'm really struggling how to split the text at the closest string to the 47th character. How is this done?

var fulltext = document.getElementById("text").value;

var a = fulltext.slice(0, 47);
console.log(a);

var b = fulltext.slice(47, 47*2);
console.log(b);

var c = fulltext.slice(94, 47*3);
console.log(c);

这是一个JS小提琴 - http://jsfiddle.net/f5n326gy/5/

Here is a JS Fiddle - http://jsfiddle.net/f5n326gy/5/

谢谢。

推荐答案

如果您只对第一部分感兴趣,请使用

If you are interested in just the first part, then use

var a = fulltext.match(/^.{47}\w*/)

请参阅演示(小提琴)此处

See demo (fiddle) here.

如果您想将整个字符串拆分为多个子字符串,请使用

If you want to split the entire string to multiple substrings, then use

var a = fulltext.match(/.{47}\w*|.*/g);

查看演示(小提琴)此处

See demo (fiddle) here.

...如果您希望子字符串不以单词分隔符开头(例如空格或逗号)并且更喜欢将它包含在上一个匹配中,然后使用

...and if you wish substrings do not start with the word separator (such as space or comma) and prefer to include it with the previous match, then use

var a = fulltext.match(/.{47}\w*\W*|.*/g);

查看演示(小提琴)这里

See demo (fiddle) here.

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

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