How to remove part of a string?

后端 未结 7 1520
夕颜
夕颜 2020-11-30 23:16

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

How do I do that?

The prefix before _ can change.

相关标签:
7条回答
  • 2020-11-30 23:47
    string = "test_1234";
    alert(string.substring(string.indexOf('_')+1));
    

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

    0 讨论(0)
  • 2020-11-30 23:49

    If you want to remove part of string

    let str = "test_23";
    str.replace("test_", "");
    // 23
    

    If you want to replace part of string

    let str = "test_23";
    str.replace("test_", "student-");
    // student-23
    
    0 讨论(0)
  • 2020-11-30 23:51

    Easiest way I think is:

    var s = yourString.replace(/.*_/g,"_");
    
    0 讨论(0)
  • 2020-12-01 00:00

    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.

    0 讨论(0)
  • 2020-12-01 00:04

    Assuming your string always starts with 'test_':

    var str = 'test_23';
    alert(str.substring('test_'.length));
    
    0 讨论(0)
  • 2020-12-01 00:05
    string = "removeTHISplease";
    result = string.replace('THIS','');
    

    I think replace do the same thing like a some own function. For me this works.

    0 讨论(0)
提交回复
热议问题