在Javascript中最近的空格处拆分文本/字符串

前端之家收集整理的这篇文章主要介绍了在Javascript中最近的空格处拆分文本/字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我真的很挣扎如何将最接近字符串的文本拆分为第47个字符.
这是怎么做到的?
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/

谢谢.

解决方法

如果您只对第一部分感兴趣,请使用
var a = fulltext.match(/^.{47}\w*/)

见demo(小提琴)here.

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

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

见demo(小提琴)here.

…如果您希望子字符串不以单词分隔符(例如空格或逗号)开头,并且希望将其包含在上一个匹配项中,那么请使用

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

见demo(小提琴)here.

原文链接:https://www.f2er.com/js/158142.html

猜你在找的JavaScript相关文章