javascript - Why would the replace with regex not work even though the regex does? -


there may simple answer this, because of familiarity (or possibly lack thereof) of replace method , how works regex.

let's have following string: abcdefhellowxyz

i want strip first 6 characters , last four, return hello, using regex... yes, know there may other ways, i'm trying explore boundaries of these methods capable of doing...

anyway, i've tinkered on http://regex101.com , got following regex worked out:

/^(.{6}).+(.{4})$/

which seems pass string , shows abcdef captured group 1, , wxyz captured group 2. when try run following:

"abcdefhellowxyz".replace(/^(.{6}).+(.{4})$/,"")

to replace captured groups "" receive empty string final output... doing wrong syntax? , if so, how 1 correct it, keeping original stance on wanting use regex in manner...

thanks in advance...

you replacing substring matches /^(.{6}).+(.{4})$/, line of code:

"abcdefhellowxyz".replace(/^(.{6}).+(.{4})$/,"") 

the regex matches whole string "abcdefhellowxyz"; thus, whole string replaced. instead, if strictly stripping lengths of extraneous substrings, use substring or substr.


edit

the answer you're looking capturing middle token, instead of outer ones:

var str = "abcdefhellowxyz";  var matches = str.match(/^.{6}(.+).{4}$/);  str = matches[1];  // index 0 entire match  console.log(str);


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -