如何从字符串中删除某个索引之后的所有字符

13
我正在尝试从指定索引处删除字符串中的所有字符。我确信有一个简单的函数可以做到这一点,但我不确定是什么。我基本上在寻找JavaScript版的C#的string.Remove函数。
4个回答

33
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];

或者

var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);

谢谢。我会尽快接受。 - msbg

3

使用子字符串

var x = 'get this test';
alert(x.substr(0,8)); //output: get this

2
你需要的是这个。
string.substring(from, to)

from : Required. The index where to start the extraction. First character is at index 0
to  : Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string

请看这里:http://www.w3schools.com/jsref/jsref_substring.asp。这是一份关于JavaScript技术的资料。

1
我建议使用slice,因为您可以使用负位置索引。通常情况下,这是更整洁的代码。例如:
var s = "messagehere";
var message = s.slice(0, -4);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接