need to modify this Regex to not remove a character - javascript

I have the following regexp (/\?(.*?)\&/) which when I use it in the following javascript code it removes the "?" from the replacement result.
href=href.replace((/\?(.*?)\&/),"")
The beginning href value is this...
/ShoppingCart.asp?ProductCode=238HOSE&CouponCode=test
I get this as my result right now...
/ShoppingCart.aspCouponCode=test
I would like to get this...
/ShoppingCart.asp?CouponCode=test
How would I modify the Regexp to do this
Thanks for you help.

Put a question mark in the replacement substring:
href=href.replace((/\?(.*?)\&/),"?")
If, say, the character can be something else than a question mark as well (say maybe a slash is a possibility), and you need to preserve which one it is, you can use a capturing group:
href=href.replace((/([?\/])(.*?)\&/),"$1")
Lookbehinds are not supported in JavaScript regexes.

To do it properly, you'll need a regex lookbehind, however this should work in your case:
href=href.replace((/\?(.*?)\&/),"?")

Related

Rex match a string in JS

I have few set of strings as mentioned below
/v4/users/1
/v4/users/1/vehicles/1
/v4/users
/v4/users?page=1
I would like to get users in all four cases as output using regex in Javascript
I tried below in https://www.regextester.com/
(?<=/v4/).*.(?=/[^/]*/)
It doesn't seem to come up right.
Any help on this would be appreciated.
You were close with the positive lookbehind. This works:
'/v4/users/1/vehicles/1'.match(/(?<=\/v4\/)[^\/\?]*/)
This matches users because after the lookbehind you match everything until just before the next slash.
/\/v4\/(\w+)/g
This will put users in a capture group. If you want you can make it a named group as well.
You can try it here:
https://regex101.com/r/0OOr0g/1

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

There may be a very simple answer to this, probably because of my familiarity (or possibly lack thereof) of the replace method and how it works with regex.
Let's say I have the following string: abcdefHellowxyz
I just want to strip the first six characters and the last four, to return Hello, using regex... Yes, I know there may be other ways, but I'm trying to explore the boundaries of what these methods are capable of doing...
Anyway, I've tinkered on http://regex101.com and got the following Regex worked out:
/^(.{6}).+(.{4})$/
Which seems to pass the string well and shows that abcdef is captured as group 1, and wxyz captured as group 2. But when I try to run the following:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
to replace those captured groups with "" I receive an empty string as my final output... Am I doing something wrong with this syntax? And if so, how does one correct it, keeping my original stance on wanting to use Regex in this manner...
Thanks so much everyone in advance...
The code below works well as you wish
"abcdefHellowxyz".replace(/^.{6}(.+).{4}$/,"$1")
I think that only use ()to capture the text you want, and in the second parameter of replace(), you can use $1 $2 ... to represent the group1 group2.
Also you can pass a function to the second parameter of replace,and transform the captured text to whatever you want in this function.
For more detail, as #Akxe recommend , you can find document on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace.
You are replacing any substring that matches /^(.{6}).+(.{4})$/, with this line of code:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
The regex matches the whole string "abcdefHellowxyz"; thus, the whole string is replaced. Instead, if you are strictly stripping by the lengths of the extraneous substrings, you could simply use substring or substr.
Edit
The answer you're probably looking for is capturing the middle token, instead of the outer ones:
var str = "abcdefHellowxyz";
var matches = str.match(/^.{6}(.+).{4}$/);
str = matches[1]; // index 0 is entire match
console.log(str);

Regex: get string between last character occurence before a comma

I need some help with Regex.
I have this string: \\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam
and want to get the result: ["dolor", "conseteteur", "diam"]So in words the word between the last backslash and a comma or the end.
I've already figured out a working test, but because of reasons it won't work in neitherChrome (v44.0.2403.130) nor IE (v11.0.9600.17905) console.There i'm getting the result: ["\loremipsumdolor,", "\sitametconseteteur,", "\sadipscingelitrseddiam"]
Can you please tell me, why the online testers aren't working and how i can achieve the right result?
Thanks in advance.
PS: I've tested a few online regex testers with all the same result. (regex101.com, regexpal.com, debuggex.com, scriptular.com)
The string
'\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam'
is getting escaped, if you try the following in the browser's console you'll see what happens:
var s = '\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam'
console.log(s);
// prints '\loremipsumdolor,\sitametconseteteur,\sadipscingelitrseddiam'
To use your original string you have to add additional backslashes, otherwise it becomes a different one because it tries to escape anything followed by a single backslash.
The reason why it works in regexp testers is because they probably sanitize the input string to make sure it gets evaluated as-is.
Try this (added an extra \ for each of them):
str = '\\\\lorem\\ipsum\\dolor,\\\\sit\\amet\\conseteteur,\\\\sadipscing\\elitr\\sed\\diam'
re = /\\([^\\]*)(?:,|$)/g
str.match(re)
// should output ["\dolor,", "\conseteteur,", "\diam"]
UPDATE
You can't prevent the interpreter from escaping backslashes in string literals, but this functionality is coming with EcmaScript6 as String.raw
s = String.raw`\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam`
Remember to use backticks instead of single quotes with String.raw.
It's working in latest Chrome, but I can't say for all other browsers, if they're moderately old, it probably isn't implemented.
Also, if you want to avoid matching the last backslash you need to:
remove the \\ at the start of your regexp
use + instead of * to avoid matching the line end (it will create an extra capture)
use a positive lookahead ?=
like this
s = String.raw`\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam`;
re = /([^\\]+)(?=,|$)/g;
s.match(re);
// ["dolor", "conseteteur", "diam"]
You may try this,
string.match(/[^\\,]+(?=,|$)/gm);
DEMO

Non-capturing groups in Javascript regex

I am matching a string in Javascript against the following regex:
(?:new\s)(.*)(?:[:])
The string I use the function on is "new Tag:var;"
What it suppod to return is only "Tag" but instead it returns an array containing "new Tag:" and the desired result as well.
I found out that I might need to use a lookbehind instead but since it is not supported in Javascript I am a bit lost.
Thank you in advance!
Well, I don't really get why you make such a complicated regexp for what you want to extract:
(?:new\\s)(.*)(?:[:])
whereas it can be solved using the following:
s = "new Tag:";
var out = s.replace(/new\s([^:]*):.*;/, "$1")
where you got only one capturing group which is the one you're looking for.
\\s (double escaping) is only needed for creating RegExp instance.
Also your regex is using greedy pattern in .* which may be matching more than desired.
Make it non-greedy:
(?:new\s)(.*?)(?:[:])
OR better use negation:
(?:new\s)([^:]*)(?:[:])

How do I convert domain.com/foo/bar/baz/ into a string like 'foo bar baz'?

Basically I want to be able to grab the ending of an url, and convert it into a string to be used somewhere.
Currently I'm doing this (which is less than optimal):
// grab the path, replace all the forward slashes with spaces
local_path = location.pathname.toString().replace(/\//g,' ');
// strip empty spaces from beginning / end of string
local_path.replace(/^\s+|\s+$/g,""));
But I think there is probably a better way. Help?
Edit: Could I confidently get rid of the .toString method there?
You could do something like this if you want to avoid regular expressions:
location.pathname.substring(1).split('/').join(' ')
That will get rid of the initial slash, but won't take care of a trailing slash. If you need to deal with those, you can omit substring and use trim for modern implementations or a regex:
location.pathname.split('/').join(' ').replace(/^\s+|\s+$/g, '')
What's wrong with what you have? Looks fine to me. That is the easiest way to handle what you want to do.
You could use the regex provided by Douglas Crockford on http://www.coderholic.com/javascript-the-good-parts/ and then split the path at the forward-slash.

Categories

Resources