up vote 1 down vote favorite
share [fb]

How can I replace underscores with spaces using a regex in Javascript?

var ZZZ = "This_is_my_name";
link|improve this question

70% accept rate
Any hint on programming language? Regex doesn't replace anything by itself. string.replace(/_/, " ") – Marcel Jackwerth Mar 18 at 18:17
Which language (looks like JavaScript)? This can be done without regex (but not in JavaScript ;)) In VIM: :%s/_/ /g – Felix Kling Mar 18 at 18:17
Regular expressions can’t replace anything. They can only describe some grammar. But many language use regular expressions to search for certain strings. So what language do you use? – Gumbo Mar 18 at 18:18
How can I replace underscores with spaces using a regex in Javascript? – Asif Akhtar Mar 18 at 18:23
feedback

4 Answers

up vote 3 down vote accepted

If it is a JavaScript code, write this, to have transformed string in ZZZ2:

var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.replace(/_/g, " ");

also, you can do it in less efficient, but more funky, way, without using regex:

var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.split("_").join(" ");
link|improve this answer
Thank u. It works. – Asif Akhtar Mar 18 at 18:29
feedback

Replace "_" with " "

The actual implementation depends on your language.

In Perl it would be:

s/_/ /g

But the truth is, if you are replacing a fixed string with something else, you don't need a regular expression, you can use your language/library's basic string replacement algorithms.

Another possible Perl solution would be:

tr/_/ /
link|improve this answer
feedback

Regular expressions are not a tool to replace texts inside strings but just something that can search for patterns inside strings. You need to provide a context of a programming language to have your solution.

I can tell you that the regex _ will match the underscore but nothing more.

For example in Groovy you would do something like:

"This_is_my_name".replaceAll(/_/," ")
    ===> This is my name

but this is just language specific (replaceAll method)..

link|improve this answer
feedback

Please refer to this post:

simple regex -- replace underscore with a space

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.