JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

Convert this_is_a_variable to thisisavariable in JavaScript

To convert this_is_a_variable to thisisavariable, call the string replace() method. You have to pass regular expression `/_/g` as the first argument and empty string "" as the second argument to the replace() method.

The following JavaScript code converts this_is_a_variable to thisisavariable:

let str = "this_is_a_variable";
str = str.replace(/_/g, '');
console.log(str); //thisisavariable

The g flag replaces all the occurrences of underscore with the empty string.

You might think why we have passed regular expression. The reason for using this is that if you pass "_" to the replace() method then only the first occurrence of underscore (_) is replaced with an empty string. To replace all the occurrences of underscore, you have to specify a regular expression with the g flag.

let str = "this_is_a_variable";
str = str.replace("_", "");
console.log(str); //thisis_a_variable

Recommended Posts