Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace substring in Javascript?

Tags:

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'

like image 343
Mohan Ram Avatar asked Dec 10 '10 15:12

Mohan Ram


People also ask

How do you replace a certain part of a string JavaScript?

JavaScript replace() Method: We can replace a portion of String by using replace() method. JavaScript has an inbuilt method called replace which allows you to replace a part of a string with another string or regular expression. However, the original string will remain the same.

What replaced Substr JavaScript?

The JavaScript String replace() method returns a new string with a substring ( substr ) replaced by a new one ( newSubstr ). Note that the replace() method doesn't change the original string. It returns a new string.

How do I replace a substring with another string?

Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).

How do you replace all occurrences of a word in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.


2 Answers

simplest:

str = str.replace(/-/g, ""); 
like image 113
ehmad11 Avatar answered Oct 14 '22 01:10

ehmad11


replace only replace the first occurrence of the substring.

Use replaceAll to replace all the occurrence.

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

str.replaceAll('-','');
like image 29
Shubham Chadokar Avatar answered Oct 14 '22 01:10

Shubham Chadokar