How to return part of string before a certain char

2019-01-18 01:58发布

问题:

If you look at the jsfiddle from question,

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

This returns all characters after the :, how can I adjust this to return all the characters before the :

something like var str_sub = str.substr(str.lastIndexOf(":")+1); but this does not work.

回答1:

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>


回答2:

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



回答3:

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



回答4:

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'))