18

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
  • 7
    Incidentally, this is plain Javascript, not jquery. Commented Dec 10, 2010 at 15:38
  • 1
    w3schools.com/jsref/jsref_replace.asp Here it is... Commented Jan 31, 2014 at 18:15

5 Answers 5

29

simplest:

str = str.replace(/-/g, ""); 
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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).
3
str.replace(/\-/g, '');

The regex g flag is global.

Comments

3

replace only replace the first occurrence of the substring.

Use replaceAll to replace all the occurrence.

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

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

Comments

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, ''));

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.