Javascript 如何删除字符串的一部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3568921/
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 part of a string?
提问by NullVoxPopuli
Let's say I have test_23and I want to remove test_.
假设我有test_23并且我想删除test_.
How do I do that?
我怎么做?
The prefix before _can change.
前面的前缀_可以改变。
回答by Andy E
My favourite way of doing this is "splitting and popping":
我最喜欢的方法是“拆分和弹出”:
var str = "test_23";
alert(str.split("_").pop());
// -> 23
var str2 = "adifferenttest_153";
alert(str2.split("_").pop());
// -> 153
split()splits a string into an array of strings using a specified separator string.
pop()removes the last element from an array and returns that element.
回答by BoltClock
Assuming your string always starts with 'test_':
假设您的字符串始终以'test_':
var str = 'test_23';
alert(str.substring('test_'.length));
回答by Yassir Ennazk
Easiest way I think is:
我认为最简单的方法是:
var s = yourString.replace(/.*_/g,"_");
回答by anonym
If you want to removepart of string
如果你想删除部分字符串
let str = "test_23";
str.replace("test_", "");
// 23
If you want to replacepart of string
如果你想替换字符串的一部分
let str = "test_23";
str.replace("test_", "student-");
// student-23
回答by gawi
string = "test_1234";
alert(string.substring(string.indexOf('_')+1));
It even works if the string has no underscore. Try it at http://jsbin.com/
如果字符串没有下划线,它甚至可以工作。在http://jsbin.com/尝试一下
回答by Stefan Stanchev
string = "removeTHISplease";
result = string.replace('THIS','');
I think replace do the same thing like a some own function. For me this works.
我认为 replace 做同样的事情就像一个自己的功能。对我来说这是有效的。

