JS regex to match spaces and non-alphanumerics




 I need a regex - well, two:  

I want a JS regex to replace all whitespace with a hyphenJavaScriptCopy Code

```
var str = 'some string';
var regex1 = ?????;
str = str.replace(regex1, '-');
```
and another to replace all non-alphanumerics with nothing - ie remove themJavaScriptCopy Code

```
regex2 = ?????;
str = str.replace(regex2, '');
```
  

  

**What I have tried:**  

  

Banging my head against a brick wall.  

Wearing a garlic necklace.  

I am armed with a wooden stake and a gun with a silver bullet.
All whitespace: `/\s/g`  

All non-alphanumerics: `/[^a-zA-Z0-9]/g`
> StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
> 
> 


(API doc for StringTokeniser)



You should do a lot better by reading one whole line at a time then splitting it (String split method) on the tab delimiters to get a String array. I haven't tested this but you should get array elements of "" where there are consecutive tabs, although it may be better to trim() the elements to get rid of any spurious blanks. try this mate. replacing images and links with your own.



```
<center><script language="JavaScript">
<!--
// Create arrays to contain all the values 
// for links and image locations
link = new Array
image = new Array

link[1]="[http://www.wildexpo.com.au/Aust%20Rep%20Show/](/posts/bad_link/469772?url=http%3A%2F%2Fwww.wildexpo.com.au%2FAust%2520Rep%2520Show%2F)"
image[1]="[http://www.reptilesaustralia.com.au/forums/Ads/wildexpo.gif](/posts/bad_link/469772?url=http%3A%2F%2Fwww.reptilesaustralia.com.au%2Fforums%2FAds%2Fwildexpo.gif)"

link[2]="[http://www.freewebs.com/langylot/](/posts/bad_link/469772?url=http%3A%2F%2Fwww.freewebs.com%2Flangylot%2F)"
image[2]="<http://i14.photobucket.com/albums/a345/Instar/reptilemad.jpg>"

link[3]="[http://www.theherphouse.com/](/posts/bad_link/469772?url=http%3A%2F%2Fwww.theherphouse.com%2F)"
image[3]="[http://www.theherphouse.com/mkportal/templates/default/images/logo.jpg](/posts/bad_link/469772?url=http%3A%2F%2Fwww.theherphouse.com%2Fmkportal%2Ftemplates%2Fdefault%2Fimages%2Flogo.jpg)"

link[4]="[http://www.aftcra.org.au/](/posts/bad_link/469772?url=http%3A%2F%2Fwww.aftcra.org.au%2F)"
image[4]="<http://i14.photobucket.com/albums/a345/Instar/adimage2.jpg>"

link[5]="<http://reptilesaustralia.com.au/index.html>"
image[5]="<http://i14.photobucket.com/albums/a345/Instar/reptilesaustralia.jpg>"

link[6]="<http://www.zoomed.com/>"
image[6]="[http://www.reptilesaustralia.com.au/forums/Ads/zoomed.jpg](/posts/bad_link/469772?url=http%3A%2F%2Fwww.reptilesaustralia.com.au%2Fforums%2FAds%2Fzoomed.jpg)"

link[7]="<http://www.reptilepark.com.au/>"
image[7]="<http://i14.photobucket.com/albums/a345/Instar/arpbanner468x60.jpg>"

link[8]="<http://www.wildlifewarriors.org.au/>"
image[8]="<http://i14.photobucket.com/albums/a345/Instar/www_banner.jpg>"

link[9]="[http://saveourreptiles.proboards50.com/index.cgi](/posts/bad_link/469772?url=http%3A%2F%2Fsaveourreptiles.proboards50.com%2Findex.cgi)"
image[9]="<http://i50.photobucket.com/albums/f335/lnvexotics/Untitled-1undoner11.jpg>"

// Create a random number between 1 and last number
random_num = (Math.round((Math.random()*8)+1))
// Write a link and images with random array
document.write('<a href="' + link[random_num] + '" target="_blank">'); 
document.write('<img src="' + image[random_num] + '" border="0"></a>'); 
-->
</script>
</center>
``` JavaScript *itself* has nothing built in for handling query string parameters. 


Code running in a (modern) browser you can use the [`URL` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) (which is part of the APIs provided by browsers to JS):





```
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
```









For older browsers (including Internet Explorer), you can use [this polyfill](https://github.com/ungap/url-search-params) or the code from the original version of this answer that predates `URL`:


You could access `location.search`, which would give you from the `?` character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.


Then you can parse it with this:





```
function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key]  "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key]  "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
```




You can get the query string from the URL of the current page with:



```
var query = window.location.search.substring(1);
var qs = parse_query_string(query);

``` How about in c++?



[http://www.1cplusplusstreet.com/vb/scripts/ShowCode.asp?txtCodeId=6877&lngWId=3](/posts/bad_link/258354?url=http%3A%2F%2Fwww.1cplusplusstreet.com%2Fvb%2Fscripts%2FShowCode.asp%3FtxtCodeId%3D6877%26lngWId%3D3) hi,

we can achieve it using dictionary and regex as the following, for example.

[[img20210826-3]](https://aws1.discourse-cdn.com/uipath/original/3x/1/5/15ac27e697226a8b24138095a41afab6793c1ea7.png "img20210826-3")
[sample20210826-3.zip](/uploads/short-url/ih67hzfqzphmctipka8hxgoocrl.zip) (3.1 kb)

hope this helps you.

regards, it looks there's nothing wrong with it 
try to copy this and paste it please. 
javascript
 const newtext = '$2, $1'; ```

<p>
    <div>
        <span&gtsomething_1</span>
        <span&gtsomething_2</span>
    </div>
</p>

``` the code you posted above still has the original img tag with joy.jpg, so it doesn't show what you entered that did not work.
but taking a wild guess, i would point out that javascript is case-sensitive, and so is the challenge checker, so if you accidentally substituted lower case for upper case, or vice-versa, it would not work in the code or pass the challenge. The existing solutions based on `findall` are fine for non-overlapping matches (and no doubt optimal except maybe for HUGE number of matches), although alternatives such as `sum(1 for m in re.finditer(thepattern, thestring))` (to avoid ever materializing the list when all you care about is the count) are also quite possible. Somewhat idiosyncratic would be using `subn` and ignoring the resulting string...:



```
def countnonoverlappingrematches(pattern, thestring):
  return re.subn(pattern, '', thestring)[1]

```

the only real advantage of this latter idea would come if you only cared to count (say) up to 100 matches; then, `re.subn(pattern, '', thestring, 100)[1]` might be practical (returning 100 whether there are 100 matches, or 1000, or even larger numbers).


Counting **overlapping** matches requires you to write more code, because the built-in functions in question are all focused on NON-overlapping matches. There's also a problem of definition, e.g, with pattern being `'a+'` and thestring being `'aa'`, would you consider this to be just one match, or three (the first `a`, the second one, both of them), or...?


Assuming for example that you want possibly-overlapping matches *starting at distinct spots in the string* (which then would give TWO matches for the example in the previous paragraph):



```
def countoverlappingdistinct(pattern, thestring):
  total = 0
  start = 0
  there = re.compile(pattern)
  while True:
    mo = there.search(thestring, start)
    if mo is None: return total
    total += 1
    start = 1 + mo.start()

```

Note that you do have to compile the pattern into a RE object in this case: function `re.search` does not accept a `start` argument (starting position for the search) the way *method* `search` does, so you'd have to be slicing thestring as you go -- definitely more effort than just having the next search start at the next possible distinct starting point, which is what I'm doing in this function. [@cssc](/u/cssc), another option would be to take the regex way.

first, it finds the index of the 5th pipe.

then, it takes the substring until that index.

give this a try:

inputstr.substring(0, regex.matches(inputstr, "\|")(4).index + 1)