Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove character from string if it starts with that character?

Tags:

string

ruby

People also ask

How do I remove all characters from a string after a specific character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do I cut a string after a specific character in C #?

Solution 1. string str = "this is a #string"; string ext = str. Substring(0, str. LastIndexOf("#") + 1);

How do you remove a character from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.


Why not just include the regex in the sub! method?

string.sub!(/^1/, '')

As of Ruby 2.5 you can use delete_prefix or delete_prefix! to achieve this in a readable manner.

In this case "1hello world".delete_prefix("1").

More info here:

https://blog.jetbrains.com/ruby/2017/10/10-new-features-in-ruby-2-5/

https://bugs.ruby-lang.org/issues/12694

'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"

N.B. you can also use this to remove items from the end of a string with delete_suffix and delete_suffix!

'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"

https://bugs.ruby-lang.org/issues/13665

I've answered in a little more detail (with benchmarks) here: What is the easiest way to remove the first character from a string?


if you're going to use regex for the match, you may as well use it for the replacement

string.sub!(%r{^1},"")

BTW, the %r{} is just an alternate syntax for regular expressions. You can use %r followed by any character e.g. %r!^1!.


Careful using sub!(/^1/,'') ! In case the string doesn't match /^1/ it will return nil. You should probably use sub (without the bang).


This answer might be more optimised: What is the easiest way to remove the first character from a string?

string[0] = '' if string[0] == '1'