How to replace underscores with spaces using a regex in Javascript

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

var ZZZ = "This_is_my_name";

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(" ");

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)..

var str1="my__st_ri_ng";
var str2=str1.replace(/_/g, ' ');

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/_/ /

To replace the underscores with spaces in a string, call the replaceAll() method, passing it an underscore and space as parameters, e.g. str.replaceAll(‘_’, ‘ ‘). The replaceAll method will return a new string where each underscore is replaced by a space.

const str="apple_pear_melon";

// ✅ without regular expression
const result1 = str.replaceAll('_', ' ');
console.log(result1); // 👉️ "apple pear melon"

// ✅ with regular expression
const result2 = str.replace(/_+/g, ' ');
console.log(result2); // 👉️ "apple pear melon"


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to interpolate variables in strings in JavaScript, without concatenation?

Similar Posts