Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 603
Karim Ali Avatar asked Mar 18 '11 18:03

Karim Ali


People also ask

How do you replace a character in a string with an underscore?

JavaScript replace() method is used to replace all special characters from a string with _ (underscore) which is described below: replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.

How do you replace a space in JavaScript?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do I remove all underscore from a string?

To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', '') . The replaceAll method will return a new string, where all underscores are removed. Copied!


3 Answers

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(" ");
like image 157
pepkin88 Avatar answered Oct 25 '22 18:10

pepkin88


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

like image 39
Jack Avatar answered Oct 25 '22 17:10

Jack


var str1="my__st_ri_ng";
var str2=str1.replace(/_/g, ' ');
like image 30
Aamir Afridi Avatar answered Oct 25 '22 17:10

Aamir Afridi