string 如何从字符串中删除某个索引后的所有字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15169858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all characters after a certain index from a string
提问by msbg
I am trying to remove all characters from a string after a specified index. I am sure there must be a simple function to do this, but I'm not sure what it is. I am basically looking for the javascript equivalent of c#'s string.Remove.
我试图从指定索引后的字符串中删除所有字符。我确信必须有一个简单的函数来做到这一点,但我不确定它是什么。我基本上是在寻找与 c# 的 string.Remove 等效的 javascript。
回答by F__M
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];
or
或者
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);
回答by Phillip Berger
You're looking for this.
你正在寻找这个。
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
See here: http://www.w3schools.com/jsref/jsref_substring.asp
回答by Sam
Use substring
使用子串
var x = 'get this test';
alert(x.substr(0,8)); //output: get this
回答by AreYouSure
I'd recommend using slice
as you can use negative positions for the index. It's tidier code in general. For example:
我建议使用,slice
因为您可以为指数使用负仓位。一般来说,它是更整洁的代码。例如:
var s = "messagehere";
var message = s.slice(0, -4);