Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all string after a space [closed]

I have this variable

c#

string text = "val1  val2";

javastript

var text = "val1  val2"

I need a example to remove everything after the space so that the result is string textModified = "val1";

Can u help me?

like image 849
Gonzalo Rivera Avatar asked Feb 12 '15 14:02

Gonzalo Rivera


5 Answers

One example would be:

c#

string text = "val1  val2";
string textModified = text.Split(' ')[0];
//Another way:
string textModified = text.IndexOf(' ');
var textModified = text.Substring(0, index);

Js

    var text = "val1  val2";
    var textModified = text.Split(' ')[0];

    // Another way:
    var index = text.indexOf(' ');
    var textModified = text.substring(0, index);
like image 171
Wilfredo P Avatar answered Oct 18 '22 05:10

Wilfredo P


In both the cases, just split on " " and take the element on index 0. The below is for javascript

alert(text.split(" ")[0]); // Javascript

And this is for c#

Console.WriteLine(text.Split(' ')[0]);
like image 38
Amit Joki Avatar answered Oct 18 '22 03:10

Amit Joki


You can use String.Remove to remove everything after space. Use String.IndexOf to find space in the string.

string text = "val1  val2";
string newText = text.Remove(text.IndexOf(' '));

You can also check if the string contains a space or not like:

if (text.Contains(' '))
{
    string newText = text.Remove(text.IndexOf(' '));
}

This will save you from the exception in case of absence of space in the string.

As for JavaScript: you can do:

console.log(text.substr(0,text.indexOf(' ')));

Should add checking for presence of space as well.

like image 34
Habib Avatar answered Oct 18 '22 03:10

Habib


here another approach with SubString

string text = "val1 val2";
int Space = text.IndexOf(' ');
string textModified = text.Substring(0, Space > 0 ? Space : text.Length);

and Linq

string text = "val1 val2";
string textModified = new string(text.TakeWhile(x => x != ' ').ToArray());
like image 1
fubo Avatar answered Oct 18 '22 05:10

fubo


Rather than splitting:

var word = text.substr(0, (text + " ").indexOf(" "));

(Swap to .Substring / .IndexOf in C#)


For fun, C# and JS (ES5) both:

var output = ""; var i = 0;
text += " ";
while (text[i] != ' ')
    output += text[i++];
like image 1
Alex K. Avatar answered Oct 18 '22 03:10

Alex K.