steve
steve

Reputation: 473

Combining two regex patterns

Is there a way of combining these two patterns? I would like to remove spaces and non-alphanumeric characters.

This does work, it just seems inefficient repeating the replace function.

var str;
str = $('p').text().replace(/[^a-zA-Z 0-9]+/g, '');
str = str.replace(/\s/g, '');

alert(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>What's Happening Here!</p>

Example jsFiddle.

Upvotes: 1

Views: 101

Answers (3)

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7171

ypu also add .replace after last like

str = $('p').text().replace(/[^a-zA-Z 0-9]+/g, '').replace(/\s/g, '');

var str;
str = $('p').text().replace(/[^a-zA-Z 0-9]+/g, '').replace(/\s/g, '');
alert(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<p>
  What 's Happening Here!
</p>

Upvotes: 0

Kevin Lynch
Kevin Lynch

Reputation: 24723

You could explicity only allow numbers and letters. This will discard any white space

str = $('p').text().replace(/[^0-9a-zA-Z]/g, '');

https://jsfiddle.net/fjnc8x4g/1/

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337714

You can combine them using the 'or' operator (|), like this: /[^a-zA-Z 0-9]+|\s/g

var str = $('p').text().replace(/[^a-zA-Z 0-9]+|\s/g, '');
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>What's Happening Here!</p>

Upvotes: 6

Related Questions