Reputation: 473
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
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
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
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