0

I have this code:

var str = ' abc'; str.replace(" ",""); 

but it is not working.

1
  • 1
    that should say "replace", right? Commented Feb 18, 2011 at 10:57

5 Answers 5

1

First, you have spelling error:

replce 

You should do:

var str = ' abc'; str = str.replace(/ /g,""); 

The /g is global modifier which will replace the specified text throughout the given string.


Alternatively, you can use split and join like this:

var str = ' abc'; str = str.split(" ").join(""); 
Sign up to request clarification or add additional context in comments.

Comments

0
var s='anishmarokey'; s.replace('a','b'); 

Comments

0

try this

var str = ' abc'; str=str.replace(/ /g,""); 

Comments

0

Try this in any browser url

javascript:alert('strin g'.replace(/ /g, '')); 

You need to use regex, not plain strings for js string.replace

var str = ' abc'; str = str.replace(/ /g, ''); 

1 Comment

The second statement won’t do what you apparently expect it to do: String.replace returns the modified string, it doesn’t change the string in-place.
0

Split the string by spaces and get the second part of the split string.

var newstr = str.split(" "); str = newstr[1]; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.