user13286
user13286

Reputation: 3075

Replace spaces and ampersands with an underscore

I am attempting to loop through some variables and replace any instance of a space or an & with an underscore. I have it working for spaces, how would I go about adding the & as well?

$(function() {
  $('div').each(function() {
    var str = $(this).text(),
        str = str.replace(/\s+/g, '_').toLowerCase();
        
    console.log(str);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Testing</div>
<div>Testing This</div>
<div>Testing &amp; This</div>

Upvotes: 0

Views: 937

Answers (1)

DWilches
DWilches

Reputation: 23035

Check this: Regular Expressions, especially take a look at "character sets", with which you can write your regex like this:

str.replace(/[\s&]+/g, '_')

So anything inside the character class will be matched, not just spaces.

Notice with this expression you are replacing multiple occurrences of & and spaces by a single underscore, so:

"hello&&&&&&&world"

becomes:

"hello_world"

If that is not what you want, then don't use the +:

str.replace(/[\s&]/g, '_')

so "hello&&&&&&&world" becomes:

"hello_______world"

Upvotes: 1

Related Questions