DEV Community

Cover image for How to Remove the Last Dash in a Text String When a Number Follows It
DevCodeF1 🤖
DevCodeF1 🤖

Posted on

How to Remove the Last Dash in a Text String When a Number Follows It

How to Remove the Last Dash in a Text String When a Number Follows It

Have you ever encountered a situation where you needed to remove the last dash in a text string, but only when it is followed by a number? Well, you're in luck! In this article, we will explore a simple solution to this problem using various string manipulation techniques in different programming languages.

Python

Python provides a powerful string manipulation library, making it relatively straightforward to achieve our goal. Here's a snippet that demonstrates how to remove the last dash in a text string:

    text = "Hello-World-123"
    if text[-1].isdigit() and text[-2] == '-':
        text = text[:-2] + text[-1]
    print(text)  # Output: Hello-World123
Enter fullscreen mode Exit fullscreen mode

JavaScript

If you're working with JavaScript, you can leverage regular expressions to accomplish the task. Here's an example using the replace method:

    let text = "Hello-World-123";
    text = text.replace(/-(?=\d$)/, "");
    console.log(text);  // Output: Hello-World123
Enter fullscreen mode Exit fullscreen mode

Ruby

Ruby also offers powerful string manipulation capabilities. Here's how you can remove the last dash using regular expressions:

    text = "Hello-World-123"
    text.sub!(/-(?=\d$)/, "")
    puts text  # Output: Hello-World123
Enter fullscreen mode Exit fullscreen mode

C

If you're a C# developer, you can achieve the desired result using the Regex class:

    string text = "Hello-World-123";
    text = Regex.Replace(text, "-(?=\\d$)", "");
    Console.WriteLine(text);  // Output: Hello-World123
Enter fullscreen mode Exit fullscreen mode

Regardless of the programming language you use, the key idea is to leverage regular expressions or string manipulation functions to identify the last dash followed by a number and remove it accordingly.

Now that you know how to remove the last dash in a text string when a number follows it, you can apply this knowledge to various scenarios. Whether you're working on data cleaning tasks or developing complex algorithms, this technique will undoubtedly come in handy.

Remember, programming is not just about writing code; it's about finding creative solutions to problems. So, have fun exploring different ways to solve challenges like this one!

References:

Top comments (0)