Skip to content Skip to sidebar Skip to footer

How To Return Part Of String Before A Certain Character?

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 adj

Solution 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><strongid="my-input">Left Text:Right Text</strong><h5>Output:</h5><strongid="my-output">XXX</strong></p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

Solution 2:

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

Solution 3:

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

Example:

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

Output will be sbstr= 01234 and not sbstr = 012345

Solution 4:

In General a function to return string after substring is

functiongetStringAfterSubstring(parentString, substring) {
    return parentString.substring(parentString.indexOf(substring) + substring.length)
}

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

Solution 5:

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

// substring(indexStart, indexEnd); // syntax// in your casestr = str.substring(0, str.indexOf(":"));

Post a Comment for "How To Return Part Of String Before A Certain Character?"