How to replace a substring in Javascript?

Replace substring.But does not work for me ...

var str='------check'; str.replace('-',''); 

Output: ----- check

JQuery removes the first '-' from my text. I need to remove all the hem from my text. My expected result: 'check'

+8
javascript
source share
4 answers

The simplest:

 str = str.replace(/-/g, ""); 
+20
source share

Try this instead:

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

.replace() does not change the original string, but returns a modified version.
For g at the end of /-/g all occurrences are replaced.

+6
source share
 str.replace(/\-/g, ''); 

The regex g flag is global.

+3
source share

You can write a short function that executes a loop and replace all occurrences, or you can use a regex.

 var str='------check'; document.write(str.replace(/-+/g, '')); 
0
source share

Source: https://habr.com/ru/post/650024/


All Articles