Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an underscore with Regex in JavaScript

Like the title says, i would like to remove an underscore within a String with a regex. This is what i have:

  function palindrome(str) {

     str = str.toLowerCase().replace(/[^a-zA-Z]/g, '',/\s/g, '',/[0-9]/g,'');  
        if (str.split("").reverse().join("") !== str) {
           return false;
        }
        else {
           return true;
        }
   }
palindrome("eye");
like image 445
olivier Avatar asked Jan 08 '16 07:01

olivier


People also ask

How do you replace all underscore with space in Javascript?

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 underscores is replaced by a space.

How do I remove dashes from a string?

Use the String. replace() method to remove all hyphens from a string, e.g. const hyphensRemoved = str. replace(/-/g, ''); . The replace() method will remove all hyphens from the string by replacing them with empty strings.

How do you remove underscore from a string in Python?

You can use the string lstrip() function to remove leading underscores from a string in Python. The lstrip() function is used to remove characters from the start of the string and by default removes leading whitespace characters.


2 Answers

Use .replace(/_/g, "") to remove all underscores or use .replace(/_/g, " ") to replace them with a space.

Here is an example to remove them:

var str = "Yeah_so_many_underscores here";
var newStr = str.replace(/_/g, "");
alert(newStr);
like image 134
void Avatar answered Sep 27 '22 20:09

void


You can use .replace to achieve this. Use the following code. It will replace all _ with the second parameter. In our case we don't need a second parameter so all _ will be removed.

<script>
var str = "some_sample_text_here.";
var newStr = str.replace(/_/g , "");
alert ('Text without underscores : ' + newStr);
</script>
like image 24
Ali Zia Avatar answered Sep 27 '22 20:09

Ali Zia