如何分割一个字符串,在一个限制n长度?

时间:2016-11-02 09:26:43

标签: javascript

我有这个字符串

It's important to remember that this function does NOT replace newlines 
with <br> tags. Rather, it inserts a <br> tag before each newline, but 
it still preserves the newlines themselves! This caused problems for me 
regarding a function I was writing -- I forgot the newlines were still 
being preserved. 

使用JavaScript,将此解析为

的最快方法是什么
var string1 = "It's important to remember that this function does ...";

这意味着,我希望限制字符串有n个长度,最后它有'...'。

帮助我。

5 个答案:

答案 0 :(得分:0)

试试这个:

var shortenedString = originalString.substring(0, n) + "..."

这有点简单,会在中间切断单词,但它可以解决问题。

答案 1 :(得分:0)

使用字符串java类中的substring方法。并且研究更好。我确信这个问题已被回答了很多次。你想要的是什么

var string1 = string0.substring(0,n);

答案 2 :(得分:0)

因为您只使用了javascript,所以这里是从https://gist.github.com/timruffles/3377784

获取的polyfill

var sample =`It's important to remember that this function does NOT replace newlines 
with <br> tags. Rather, it inserts a <br> tag before each newline, but 
it still preserves the newlines themselves! This caused problems for me 
regarding a function I was writing -- I forgot the newlines were still 
being preserved.`;

var chunk = function(array,chunkSize) {
	return array.reduce(function(reducer,item,index) {
		reducer.current.push(item);
		if(reducer.current.length === chunkSize || index + 1 === array.length) {
			reducer.chunks.push(reducer.current);
			reducer.current = [];
		}
		return reducer;
	},{current:[],chunks: []}).chunks
};

var data = chunk(sample.split(/[ ]+/), 10);
data.forEach(function(line){
console.log(line.join(" "))
});

答案 3 :(得分:0)

如果你不想在中间切词:

r.db("mydb").table("users").filter(doc => doc("name").eq('Peter')
    .or(doc("name").eq('John')).and(doc('age').eq(30)));

输出:

  • 这很重要......
  • 这是......
  • 重要的是要记住这一点 函数不会用...替换换行符。

答案 4 :(得分:0)

标准JavaScript提供了三种String方法,可让您在位置n处剪切字符串:

只需使用其中一种方法,并在结果的末尾添加...

演示1

var myString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var n = 5;
var output = '';

output += myString.slice(0, n) + '...' + '\n<br>';      // Option 1
output += myString.substring(0, n) + '...' + '\n<br>';  // Option 2
output += myString.substr(0, n) + '...';                // Option 3

document.body.innerHTML = output;

另见this Fiddle

演示2

如果您想经常这样做,您可能希望将其包装在一个函数中:

var myString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var output = '';

function shorten(str, n) {
    if(n > 0) {
        return str.slice(0, n) + '...';
    }
    return '...';
}

output += shorten(myString, 20) + '\n<br>';   
output += shorten(myString, 8) + '\n<br>'; 
output += shorten(myString, 0);

document.body.innerHTML = output;

另见this Fiddle