Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 adjust this to return all the characters before the :

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

like image 404
Smudger Avatar asked May 09 '13 20:05

Smudger


People also ask

How do you return part of a string after a certain character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character.

How do you get the part of a string before a specific character in Python?

Python Substring Before Character You can extract a substring from a string before a specific character using the rpartition() method. What is this? rpartition() method partitions the given string based on the last occurrence of the delimiter and it generates tuples that contain three elements where.

How do you cut a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do I trim a string before a specific character in C#?

You can use the IndexOf method and the Substring method like so: string output = input. Substring(input. IndexOf('.


2 Answers

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; } 
like image 149
Hexodus Avatar answered Oct 25 '22 22:10

Hexodus


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

like image 26
A. James McHale Avatar answered Oct 25 '22 23:10

A. James McHale