How to get text between two characters?

后端 未结 6 1131
难免孤独
难免孤独 2020-12-06 04:55

|text to get| Other text.... migh have \"|\"\'s ...

How can I get the text to get stuff from the string (and remove it)?

It should

相关标签:
6条回答
  • 2020-12-06 05:09

    To get it:

    "|text to get| Other text.... migh have \"|\"'s ...".match(/\|(.*?)\|/)
    

    To remove it:

    "|text to get| Other text.... migh have \"|\"'s ...".replace(/\|(.*?)\|/, "")
    

    I'm not the expert on Regex so if someone has improvements, please edit.

    0 讨论(0)
  • 2020-12-06 05:13
    var test_str = "|text to get| Other text.... migh have \"|\"'s ...";
    var start_pos = test_str.indexOf('|') + 1;
    var end_pos = test_str.indexOf('|',start_pos);
    var text_to_get = test_str.substring(start_pos,end_pos)
    alert(text_to_get);
    
    0 讨论(0)
  • 2020-12-06 05:14
    string = '|text to get| Other text.... migh have "|"\'s ...';
    string = string.replace(/^\|[^|]*\|/, '');
    
    0 讨论(0)
  • 2020-12-06 05:19

    You don't need a regular expression for this; firing up the regex engine is completely overkill for such a simple task.

    Just use basic string manipulation:

    function getSubStr(str, delim) {
        var a = str.indexOf(delim);
    
        if (a == -1)
           return '';
    
        var b = str.indexOf(delim, a+1);
    
        if (b == -1)
           return '';
    
        return str.substr(a+1, b-a-1);
        //                 ^    ^- length = gap between delimiters
        //                 |- start = just after the first delimiter
    }
    
    print(getSubStr('|text to get| Other text.... migh have "|"s ...', '|'));
    
    // Output: text to get
    

    Live demo.

    0 讨论(0)
  • 2020-12-06 05:19

    you should look up the following functions:

    split()
    substr()
    

    Depending on how you want to solve your task either can be used.

    0 讨论(0)
  • 2020-12-06 05:21

    You'll have to get the text you want by using match, then run replace with it:

    var text = "|text to get| Other text.... migh have \"|\"'s ...";
    text.replace(text.match(/\|([^|]*)\|/)[1], "");
    
    0 讨论(0)
提交回复
热议问题