1

Suppose I have a string hello and I want it to subtract from the strings.

  • hello_my_good_world
  • my_hello_good_world
  • my_good_hello_world

And the output from above strings must be like following respectively.

  • my_good_world
  • my_good_world
  • my_good_world

Please note that how underscore _ got removed too. If string hello is at the start then it should remove underscore ahead, If it is in the middle then it should remove either next or previous underscore. So I don't have duplicate underscores. And if substring is at the end then it should remove previous underscore. I tried using JS replace method but I can remove only substring. Haven't figured out how to handle duplicate underscores to eliminate them too.

3 Answers 3

8

use .replace(/hello_|_hello/g,'')

console.log("hello_my_good_world".replace(/hello_|_hello/g,''))
console.log("my_hello_good_world".replace(/hello_|_hello/g,''))
console.log("my_good_hello_world".replace(/hello_|_hello/g,''))

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Bro.. Worked perfectly as expected.
3

You could also do multiple replacements.

const tests = [
    'hello_my_good_world',
    'my_hello_good_world',
    'my_good_hello_world',
]

const replaced = tests.map(s => {
    const replacement = s
        .replace('hello', '')   // eliminate 'hello'
        .replace('__', '_')     // eliminate double underscore
        .replace(/^_/g, '')     // eliminate leading underscore
        .replace(/_$/g, '')     // eliminate trailing underscore
    
    return replacement;
});

console.log({
    replaced,
});

Comments

2

Another option is to split the string on _, filter out "hello", and rejoin with _:

console.log("hello_my_good_world".split("_").filter(s => s !== "hello").join("_"))
console.log("my_hello_good_world".split("_").filter(s => s !== "hello").join("_"))
console.log("my_good_hello_world".split("_").filter(s => s !== "hello").join("_"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.