17

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 5

29

simplest:

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

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
  • 3
    jAndy, your regular expression is inside a string literal, you need to do away with the ' for this to work :-) (Also, it's not necessary to escape the hyphen, which has no special meaning outside of a character class).
    – Andy E
    Dec 10, 2010 at 15:42
3
str.replace(/\-/g, '');

The regex g flag is global.

3

replace only replace the first occurrence of the substring.

Use replaceAll to replace all the occurrence.

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

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

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.