How to return part of string before a certain character?

前端 未结 4 1329
谎友^
谎友^ 2020-12-08 18:49

If you look at the jsfiddle from question,

var str = \"Abc: Lorem ipsum sit amet\";
str = str.substring(str.indexOf(\":\") + 1);

This retur

相关标签:
4条回答
  • 2020-12-08 19:23

    And note that first argument of subString is 0 based while second is one based.

    Example:

    String str= "0123456";
    String sbstr= str.substring(0,5);
    

    Output will be sbstr= 01234 and not sbstr = 012345

    0 讨论(0)
  • 2020-12-08 19:31

    You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

    str.substring(0, str.indexOf(":"));

    Where 'str' represents the variable with your string inside.

    Click here for JSFiddle Example

    Javascript

    var input_string = document.getElementById('my-input').innerText;
    var output_element = document.getElementById('my-output');
    
    var left_text = input_string.substring(0, input_string.indexOf(":"));
    
    output_element.innerText = left_text;
    

    Html

    <p>
      <h5>Input:</h5>
      <strong id="my-input">Left Text:Right Text</strong>
      <h5>Output:</h5>
      <strong id="my-output">XXX</strong>
    </p>
    

    CSS

    body { font-family: Calibri, sans-serif; color:#555; }
    h5 { margin-bottom: 0.8em; }
    strong {
      width:90%;
      padding: 0.5em 1em;
      background-color: cyan;
    }
    #my-output { background-color: gold; }
    
    0 讨论(0)
  • 2020-12-08 19:31

    Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

    0 讨论(0)
  • 2020-12-08 19:35

    In General a function to return string after substring is

    function getStringAfterSubstring(parentString, substring) {
        return parentString.substring(parentString.indexOf(substring) + substring.length)
    }
    
    function getStringBeforeSubstring(parentString, substring) {
        return parentString.substring(0, parentString.indexOf(substring))
    }
    console.log(getStringAfterSubstring('abcxyz123uvw', '123'))
    console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))

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