I would like to remove everything after a space in a string.
For example:
"my string is sad"
should return
"my"
I've been trying to figure out how to do this using sub/gsub but have been unsuccessful so far.
Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .
Java has inbuilt methods to remove the whitespaces from the string whether leading, trailing, both, or all. trim() method removes the leading and trailing spaces present in the string. strip method removes the leading and trailing spaces present in the string. Also, it is Uniset/Unicode character aware.
Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.
If you want to delete all the text after a character or string (to the right) in Notepad++ you would need to make use of regex. So, simply add . * to delete all characters after the string or character on each that you want to delete from a line.
You may use a regex like
sub(" .*", "", x)
See the regex demo.
Here, sub
will only perform a single search and replace operation, the .*
pattern will find the first space (since the regex engine is searching strings from left to right) and .*
matches any zero or more characters (in TRE regex flavor, even including line break chars, beware when using perl=TRUE
, then it is not the case) as many as possible, up to the string end.
Some variations:
sub("[[:space:]].*", "", x) # \s or [[:space:]] will match more whitespace chars
sub("(*UCP)(?s)\\s.*", "", x, perl=TRUE) # PCRE Unicode-aware regex
stringr::str_replace(x, "(?s) .*", "") # (?s) will force . to match any chars
See the online R demo.
strsplit("my string is sad"," ")[[1]][1]
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