Mohan Ram
Mohan Ram

Reputation: 8463

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'

Upvotes: 18

Views: 48530

Answers (5)

Shubham Chadokar
Shubham Chadokar

Reputation: 2763

replace only replace the first occurrence of the substring.

Use replaceAll to replace all the occurrence.

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

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

Upvotes: 3

jAndy
jAndy

Reputation: 235962

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.

Upvotes: 7

ehmad11
ehmad11

Reputation: 1395

simplest:

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

Upvotes: 29

simshaun
simshaun

Reputation: 21466

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

Upvotes: 0

John Giotta
John Giotta

Reputation: 16934

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

The regex g flag is global.

Upvotes: 3

Related Questions