Why did one $ disappear? [duplicate] - javascript

This question already has answers here:
JavaScript replace() method dollar signs
(6 answers)
Closed 3 years ago.
let str = '$$double_dollars$$'
console.log(str.replace('$$double_dollars$$', '$$no_double_dollars$$'));
// => $no_double_dollars$
// expected $$no_double_dollars$$
Why is this happening? How to work around this bug?

According to the MDN docs for String.prototype.replace (as what #Alex states), there is a list of special patterns which are evaluated accordingly and one of them is what you're using.
The special pattern is as follows:
$$ inserts a $
See the MDN docs for the full list of special patterns.
And as what #H.Figueiredo has commented, you can escape the dollar signs or follow one of the answers posted seconds after this answer.

See: MDN - String.prototype.replace # Specifying a function as a parameter
The replacement string can include the following special replacement patterns:
Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n Where n is a positive integer less than 100, inserts the nth parenthesized
submatch string, provided the first argument was a RegExp object.
Note that this is 1-indexed.
let str = '$$double_dollars$$'
console.log(str.replace('$$double_dollars$$', '$$$$yes_double_dollars$$$$'));
// => $$yes_double_dollars$$

See the documentation for passing a replacement String to replace.
$ is a special character. To express a literal $, use $$.
let str = '$$double_dollars$$'
console.log(str.replace('$$double_dollars$$', '$$$$result$$$$'));

Related

Why does this regex not exclude hyphens or brackets? [duplicate]

This question already has answers here:
Why this javascript regex doesn't work?
(1 answer)
Match exact string
(3 answers)
Closed 5 years ago.
Regex is the bane of my existence. I've done plenty tutorials, but the rules never stick, and when I look them up they seem to conflict. Anyways enough of my whining. Could someone tell me why this regex doesn't exclude hyphens or brackets:
/^[A-Za-z_][A-Za-z\d_]*/
The way I understand it (or at least what I'm trying to do), the ^ character dictates that the regex should start with the next thing on the list That means the regex should start with [A-Za-z_] or any character a-z and A-Z as well as and underscore _. Then the string can have anything that includes [A-Za-z\d_] which is any alphanumeric character and an underscore. Then I use the * to say that the string can have any number of what was presented previously (any alphanumeric character plus underscore). At no point to I specify a bracket [ or a hyphen -. Why does this expression not exclude these characters
Extra info
I'm verifying this with javascript:
function variableName(name) {
const reg = RegExp("^[A-Za-z_][A-Za-z\d_]*")
return reg.test(name)
}
function variableName("va[riable0") // returns true should be false
It's actually matching the first 2 letters("va"), that's why it's true.
To match the whole phrase, your reg expression should have "$" at the end:
"^[A-Za-z_][A-Za-z\d_]*$"
Your regex matches the part of the string that does not contain the bracket, because your're missing the $ anchor that would (together with ^) force it to match the whole string. Use
const reg = /^[A-Za-z_][A-Za-z\d_]*$/g
// ^
function variableName(name) {
return reg.test(name)
}
console.log(variableName("va[riable0"))

Matching the string "/$" in a RegExp constructor [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I'm trying to match the phrase "/$" using the RegExp constructor, but no amount of escaping seems to help. Am is missing something?
RegExp("\/\$").test("/$")
// false
RegExp("/$").test("/$")
// false
RegExp("\/$").test("/$")
// false
RegExp("/\$").test("/$")
// false
You need to use \\ instead of \ and there is no need to escape / or use regex /\/\$/ directly. Check RegExp documentation for more info.
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
For example, /\w+/ is equivalent to new RegExp('\\w+')
console.log(
RegExp("/\\$").test("/$")
)
//or
console.log(
/\/\$/.test("/$")
)
Refer : Javascript regular expression - string to RegEx object

JavaScript string.replace using "$$" outputs "$" [duplicate]

This question already has answers here:
`string.replace` weird behavior when using dollar sign ($) as replacement
(3 answers)
Closed 7 years ago.
Can anyone explain to me why JavaScript outputs a single $ when using $$ as the replace value?
"hi".replace("hi", "$$bye$$");
"hi".replace("hi", "\$\$bye\$\$");
//both output -> $bye$
//but I expected $$bye$$
The $ acts as a metacharacter in the replacement strings for that function. The string $$ is used to indicate that you just want a $. Otherwise, $ followed by a digit refers to the contents of a capturing group from the regular expression. As an example:
alert("aaabbb".replace(/(a+)(b+)/, "$2$1")); // bbbaaa
The string "\$\$bye\$\$" is exactly the same as the string "$$bye$$". Because $ is not a metacharacter in the string grammar, the backslash preceding it will be ignored.
You can double-up on the backslashes to have them survive the string constant parse, but the .replace() function will pay no particular attention do them, and you'll get \$\$ in the result.

How do I include an inline comment in a regular expression in JavaScript [duplicate]

This question already has answers here:
Commenting Regular Expressions
(7 answers)
Closed 3 years ago.
Inline comments works when a string passed to the RegExp constructor:
RegExp("foo"/*bar*/).test("foo")
but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?
Javascript supports neither the x modifier, nor inline comments (?#comment). See here.
I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):
RegExp(
"foo" + // match a foo
"bar" + // followed by a bar
"$" // at the end of the string
).test("somefoobar");
Other than using a zero-length sub-expression, it's not possible. Examples of "comments":
/[a-z](?!<-- Any letter)/
(?!..) is a negated look-ahead. It matches if the previous is not followed by the string within the parentheses. Since the thing between (?! and ) is a real regular (sub)expression, you cannot use arbitrary characters unless escaped with a backslash
An alternative is to use the positive look-ahead:
/[a-z](?=|<-- Any letter)/
This look-ahead will always match, because obviously the a-z is also followed by an empty string.

Change date format in javascript (jquery)

I have two dates:
var first = '21-11-2012';
var second = '03-11-2012';
What is the best way to format it like this:
var first = '2012-11-21';
var second = '2012-11-03';
Should I use jQuery or simply JavaScript?
You don't need jQuery for this, simply use JavaScript like so:
function formatDate(d){
return d.split('-').reverse().join('-');
}
Although if you want more reusable code consider using the JavaScript Date Object.
No need to be thinking of jQuery for basic string manipulation: the standard JS String methods are more than adequate, which (I assume) is why jQuery doesn't actually have equivalent methods.
A regex .replace() or the split/reverse/join concept in the other answers can both do it in one line. I'd recommend getting familiar with the methods at the MDN page I linked to, but meanwhile:
first = first.replace(/^(\d\d)-(\d\d)-(\d\d\d\d)$/,"$3-$2-$1");
(Same for second - encapsulate in a function if desired.)
This uses a regular expression to match the different parts of the date and reverse them.
UPDATE - As requested, an explanation of the regex I used:
^ // match beginning of string
(\d\d) // match two digits, and capture them for use
// in replacement expression as $1
- // match the literal hyphen character
(\d\d) // match two digits, and capture for use as $2
- // match the literal hyphen character
(\d\d\d\d) // match four digits, and capture for use as $3
$ // match end of string
Because the pattern matches from beginning to end of string the whole string will be replaced. The parts of the expression in parentheses are "captured" and can be referred to as $1, $2, etc. (numbered in the order they appear in the expression) if used in the replacement string, so "$3-$2-$1" reverses the order of these captured pieces and puts hyphens between them. (If the input string didn't meet that format the regex would not match and no replacement would be made.)
first=first.split("-").reverse().join("-")
second=second.split("-").reverse().join("-")

Categories

Resources