req.url.replace(/\/?(?:\?.*)?$/, '') node js [duplicate] - javascript

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
Meaning of javascript text between two slashes
(3 answers)
Closed 2 years ago.
I'm referring to a book and it has code I can't understand:
http.createServer(function(req,res){
// normalize url by removing querystring, optional
// trailing slash, and making lowercase
var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
}
I have a problem in the following line:
var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
What is that first argument of replace method?

The first argument is the pattern, a regex on what to look for, and the second argument is to what to replace the instances with. In this case, \/? is the / character with zero or one instance of it, and (?:\?.*)? not to capture the piece where it has ? zero to unlimited times.

Related

How to find out if a string contains all characters in a set of characters [duplicate]

This question already has answers here:
Test If String Contains All Characters That Make Up Another String
(4 answers)
Closed 2 years ago.
I have been struggling with a regex pattern to find out if a string contains all characters in a set of characters.
e.g I want to test if "sheena" contains esnh, I should get a match but if I want to test if "sheena" contains esnk, I should not get a match because there exist no k in "sheena" even thought esn exists.
To solve this problem just use the every method.
const matchString = (str, matcher) => [...matcher].every(n => str.includes(n));
console.log(matchString('sheena', 'eshn'));
console.log(matchString('sheena', 'eshk'));

Find a specific value of a string between two chars/strings without knowing its value [duplicate]

This question already has answers here:
Get Substring between two characters using javascript
(24 answers)
Closed 2 years ago.
String example: "{something}" or "{word: something}"
What I need to do is get 'something', so the text between two specific parts of the string, in these case {-} and {word:-} (The 'something' part can change in every string, I never know what it is).
I tried using string.find() or regex but I didn't come up with a conclusion. What's the quickest and best way to do this?
What you need is a capture group inside a regex.
> const match = /\{([^}]+)\}/.exec('{foo}')
> match[1]
'foo'
The stuff in the parens, ([^}]+), matches any character but }, repeated at least once. The parens make it be captured; the first captured group is indexed as match[1].

How to replace all / with - from string [duplicate]

This question already has answers here:
Replace forward slash "/ " character in JavaScript string?
(9 answers)
Why this javascript regex doesn't work?
(1 answer)
Closed 4 years ago.
I have a string field 01/01/1986 and I am using replace method to replace all occurrence of / with -
var test= '01/01/1986';
test.replace('//g','-')
but it does't give desire result. Any pointer would be helpful.
You just have a couple issues: don't put the regex in quotes. That turns it into a string instead of a regex and looks for that literal string. Then use \/ to escape the /:
var test= '01/01/1986';
console.log(test.replace(/\//g,'-'))
A quick way is to use split and join.
var test= '01/01/1986';
var result = test.split('/').join('-');
console.log(result);
Note too that you need to save the result. The original string itself will never be modified.

js regexp - to escape character, needs one backward slash? or two? [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
How to properly escape characters in regexp
(4 answers)
Closed 4 years ago.
I can't understand when I need one and two backward slashes \.
First, see an example:
const rxHttps = new RegExp("\/");
console.log(rxHttps.test("/")); // true
const rxQuestion = new RegExp("\\?");
console.log(rxQuestion.test("?")); // true
const rxAnotherQuestion = new RegExp("\?"); // Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
In the above example, to use a character /, it needs just one \.
However, ? needs two \, or SyntaxError occurs.
This is really confusing. I can't make heads or tails of it.
Why are they different? Am I misunderstanding?
because '?' is used to mean that what's before it can or not exist like {0,}
for example
var reg = new RegExp('a?');
// this has the same meaning as using
// var reg = new RegExp('a\?');
reg.test('a'); // will display true
reg.test('anything'); // this will also display true
reg.test('123'); // this also displays true
so if you want to check of the existence of '?' character, you have to escape it, and since it's used as '\?' also, then you have to escape it using '\?'
Why does it give you syntax error ?
because it's expecting something to check if it exists or not and you're not giving it anything.

Replace '-' with '--' in a JavaScript string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I am trying to replace a single dash '-' character in a string with double dashes.
2015–09–01T16:00:00.000Z
to be
2015-–09-–01T16:00:00.000Z
This is the code I am using but it doesn't seem to be working:
var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.
In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.
For example,
var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');
Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to – and it is not the same as hyphen (-). The character codes for those characters are as follows
console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
The hyphen character – you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.
The correct RegExp in this case is temp.replace(/–/g,'--')
Probably the easiest thing would be to just use split and join.
var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");

Categories