19

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");
6
  • 2
    This should work. What is not working? Note: You don't need toLowerCase(). Commented Jan 8, 2016 at 7:12
  • yes, but it seems that the underscores aren't removed. Commented Jan 8, 2016 at 7:12
  • 1
    You need to assign the result str = str.replace... to the variable. Commented Jan 8, 2016 at 7:12
  • @Tushar i did this in my code Commented Jan 8, 2016 at 7:13
  • 1
    .replace(/[^a-zA-Z]/g, '',/\s/g, '',/[0-9]/g,'') you can't use replace like this. You can chain them .replace(/[^a-zA-Z]/g, '').replace(/\s/g, '').replace(/[0-9]/g,''). In your case you don't need this, you can use str.replace(/_/g, ''); Commented Jan 8, 2016 at 7:16

4 Answers 4

48

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

Sign up to request clarification or add additional context in comments.

Comments

4
str.replace(/_/g, '');

This should work.

Comments

3

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>

Comments

1

you can remove underscore from response or any string like this: "hello_rizo"

Code:

var rizo="hello_rizo"
console.log('output', e.response.data.message.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));

output: hellorizo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.