How to Replace Substring in Javascript?

To replace substring.But not working for me...

var str='------check';

str.replace('-','');

Output: -----check

Jquery removes first '-' from my text. I need to remove all hypens from my text. My expected output is 'check'

2

5 Answers

simplest:

str = str.replace(/-/g, ""); 
0

Try this instead:

str = str.replace(/-/g, '');

.replace() does not modify the original string, but returns the modified version.
With the g at the end of /-/g all occurences are replaced.

1
str.replace(/\-/g, '');

The regex g flag is global.

replace only replace the first occurrence of the substring.

Use replaceAll to replace all the occurrence.

var str='------check';

str.replaceAll('-','');

You can write a short function that loops through and replaces all occurrences, or you can use a regex.

var str='------check';

document.write(str.replace(/-+/g, ''));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest