如何在Javascript中将字符串修剪为N个字符? [英] How to trim a string to N chars in Javascript?

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

问题描述

我怎样才能使用Javascript创建一个函数来修剪作为参数传递的字符串到指定的长度,也作为参数传递。例如:

How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:

var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);

// trimmedString should be:
// "this is"

有人有想法吗?我听说过使用子字符串,但不太明白。

Anyone got ideas? I've heard something about using substring, but didn't quite understand.

推荐答案

为什么不使用子字符串... string.substring(0,7); 第一个参数(0)是起点。第二个参数(7)是结束点(不包括)。 此处提供更多信息。

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

这篇关于如何在Javascript中将字符串修剪为N个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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