How to get text between two characters?

后端 未结 6 1132
难免孤独
难免孤独 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: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.

提交回复
热议问题