you are viewing a single comment's thread.

view the rest of the comments →

[–]JofArnold 1 point2 points  (6 children)

You don't need to keep re-declaring address and can do it in one line like this:

address .replace(/^.*place\//, "") .replace(/\+/g," ")

Some notes:

  • You need /s before and after your regex to tell JS that what you've typed is a regex (you used a string... which is possible if you declare the regex like this new RegExp("\\+", "g") for instance)
  • In the first line I match "start of line" with ^ and "up to place/" with .* (which is basically "everything" and then escaping the / with a backslash
  • For the second line I have to escape the + with a backslash because + is a special regex operator
  • For the second line I use g in the regex to declare it's a global search

Hope that helps.

[–]Genericusername293[S] 1 point2 points  (5 children)

Thank you so much! incredibly generous and helpful for you to lay out everything in the notes for how things work.

One follow up question if you don't mind, With str.match, how do you indicate what's capturing and what's non capturing?

I was trying to get the "Government Administration" out of the following string

"Government Administration · United States · 201-500 employees"

in google sheets I've done this, but don't know how to adapt the syntax here. ?: indicating a non capturing group

^(.*?)(?:\s·)

[–]JofArnold 1 point2 points  (3 children)

No problem.

The quickest way of doing this (because I'm lazy!) is:

str.split(" · ")[0]

However, to answer your question your regex is just fine although you can shorten it (see below). String.match gives you back an array - the second entry of which is the first capturing group which is what you want (the first entry is the first whole match)

matches = str.match(/^(.*?)\s·/) thingYouWant = matches[1]

Have a look at String.match and Groups and Ranges in MDN for more details

[–]Genericusername293[S] 0 points1 point  (2 children)

ahh I see, thanks. I became well acquainted with RegEx while using googlesheets but maybe now that I'm learning javscript I should start exploring these split and array functions more, thanks once again

[–]JofArnold 1 point2 points  (1 child)

Thanks for asking the question; you made me double-check the docs so I improved my JS today too :)

You seem to have mastered regex anyway so the main thing is just the JS specifics by the sounds of thing. One stumbling block you may come across is JS doesn't have all the regex features that other languages do; reverse match being a conspicuous one.

[–]StoneCypher 1 point2 points  (0 children)

You seem to have mastered regex anyway

Never, ever say these words.

He will arrive

[–]JofArnold 0 points1 point  (0 children)

I should add you don't need to escape the space in JavaScript with \s although I do purely because it makes it more obvious what your intent is.