开发者

How to remove part of a string?

开发者 https://www.devze.com 2023-01-13 16:47 出处:网络
Let’s say I have test_23 and I want to remove test_. How do I do that? 开发者_StackOverflowThe prefix before _ can change.My favourite way of doing this is \"splitting and popping\":

Let’s say I have test_23 and I want to remove test_.

How do I do that?

开发者_StackOverflowThe prefix before _ can change.


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.


If you want to remove part of string

let str = "try_me";
str.replace("try_", "");
// me

If you want to replace part of string

let str = "try_me";
str.replace("try_", "test_");
// test_me


Assuming your string always starts with 'test_':

var str = 'test_23';
alert(str.substring('test_'.length));


Easiest way I think is:

var s = yourString.replace(/.*_/g,"_");


string = "test_1234";
alert(string.substring(string.indexOf('_')+1));

It even works if the string has no underscore. Try it at http://jsbin.com/


let text = 'test_23';
console.log(text.substring(text.indexOf('_') + 1));


You can use the slice() string method to remove the begining and end of a string

const str = 'outMeNo';

const withoutFirstAndLast = str.slice(3, -2);
console.log(withoutFirstAndLast);// output-->  'Me'

0

精彩评论

暂无评论...
验证码 换一张
取 消