1

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
steve
  • 471
  • 6
  • 15
  • 1
    Possible duplicate of [Combining regular expressions in Javascript](https://stackoverflow.com/questions/9213237/combining-regular-expressions-in-javascript) – Jan Stoltman Dec 14 '17 at 11:29

3 Answers3

6

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

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/

Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
0

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>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39