Let’s say I have test_23 and I want to remove test_.
test_23
test_
How do I do that?
The prefix before _ can change.
_
假设字符串总是以 'test_'开头:
'test_'
var str = 'test_23'; alert(str.substring('test_'.length));
我最喜欢的方法是“劈啪作响”:
var str = "test_23"; alert(str.split("_").pop()); // -> 23 var str2 = "adifferenttest_153"; alert(str2.split("_").pop()); // -> 153
Split () 使用指定的分隔符字符串将字符串分隔为字符串数组。 pop() removes the last element from an array and returns that element.
string = "test_1234"; alert(string.substring(string.indexOf('_')+1));
It even works if the string has no underscore. Try it at http://jsbin.com/
我认为最简单的方法是:
var s = yourString.replace(/.*_/g,"_");
如果你想 拿开字符串的一部分
let str = "try_me"; str.replace("try_", ""); // me
如果你想 更换字符串的一部分
let str = "try_me"; str.replace("try_", "test_"); // test_me
let text = 'test_23'; console.log(text.substring(text.indexOf('_') + 1));
可以使用 slice ()字符串方法删除字符串的开头和结尾
const str = 'outMeNo'; const withoutFirstAndLast = str.slice(3, -2); console.log(withoutFirstAndLast);// output--> 'Me'