在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*/)
在这里看演示(小提琴)。
如果要将整个字符串拆分为多个子字符串,请使用
var a = fulltext.match(/.{47}\w*|.*/g);
在这里看演示(小提琴)。
…如果您希望子字符串不以单词分隔符(例如空格或逗号)开头,并且希望将其与前一个匹配项包含在一起,那么请使用
var a = fulltext.match(/.{47}\w*\W*|.*/g);
在这里看演示(小提琴)。
您可以使用带有fromIndex
第二个参数的indexOf
方法找到下一个单词边界。 之后,您可以使用slice
来获得左侧或右侧。
var fulltext = "The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument."; var before = fulltext.slice(0, fulltext.indexOf(' ', 47)); var after = fulltext.slice(fulltext.indexOf(' ', 47)); alert(before); alert(after);