How to return part of string before a certain character?

前端 未结 4 1346
谎友^
谎友^ 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: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

    Input:
    Left Text:Right Text
    Output:
    XXX

    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; }
    

提交回复
热议问题