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?
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);
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]);
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.
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());
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++];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With