String .replace() does not work with '$' symbol [duplicate] - javascript

This question already has answers here:
How can I replace all occurrences of a dollar ($) with an underscore (_) in javascript?
(4 answers)
Closed 4 years ago.
So, I cannot figure out what is wrong? I know that .replace() returns a new string, without mutable existing. It's really ridiculous, but I'm stuck on this. I need to replace '$' on '2', but it just concat string, not replace the value...
var answer_form = '$0';
var question_num = 2;
answer_form = answer_form.replace(/$/g, question_num);
console.log(answer_form);

$ in regex means the end of a string. Use " if you do not want to use regular expressions or escape the character like this: \$.
var answer_form = '$0';
var question_num = 2;
answer_form = answer_form.replace(/\$/g, question_num);
console.log(answer_form);

var answer_form = '$0';
var question_num = 2;
answer_form = answer_form.replace(/[$]/g, question_num);
console.log(answer_form);

The first argument in String.replace method can be a regular expression or a String.
In your example, you are using regular expression, in which $ has a special meaning, which matches end of string. To match a literal $, you will have to escape using \, as in the following example -
answer_form = answer_form.replace(/\$/g, question_num);

Related

Reading anything between {{ and }} regex in JavaScript [duplicate]

This question already has answers here:
regex get anything between double curly braces
(3 answers)
Closed 5 days ago.
I would like to get any string between {{ and }} using Regex. for example {{user.email}} should return user.email. To achieve this I have written the below Regex:
const str = '{{user.email}}'
const regExp = /{{([^]*?)}}/g
const variableName = str.match(regExp)
console.log(variableName) // returns ['{{user.email}}'] only not 'user.email'
This is the link for working regexp:
https://regex101.com/r/UdbrT9/1
I'm I missing something ?
Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions.
const str = '{{user.email}}test{{tos}}{{done}}'
const regExp = /(?<=\{\{)(.*?)(?=\}\})/g
const variableName = str.match(regExp);
console.log(variableName)
Your regexp looks correct.
However, the actual "match" is the full string.
What you want is the first captured group (inside parenthesis).
const str = "{{user.email}}";
const regexp = /{{([^]*?)}}/g
const match = regexp.exec(str);
console.log(match[1]); // First captured group in match
Note the use of RegExp::exec() (that contains the full match + the captured group. Unfortunately String::match() does not, it just returns the full match.
Why don't you use replace?
string.replace(/{{|}}/g, '') or replaceAll

JavaScript replace regex with array element [duplicate]

This question already has an answer here:
Why this javascript regex doesn't work?
(1 answer)
Closed 3 years ago.
Trying to replace everything inside brackets [ ] with an element of an array. Example:
function replacingText(){
var names = ["Cole", "Kyle", "Chase"];
var sentance = 'This is [Cole].'
var regex = "\[(.*?)\]/gm";
console.log(sentance.replace(regex, names[1]));
}
So the output should be 'This is Kyle.' instead of 'This is [Cole].'
The only thing that needs fixed is the regex string needs to be
var regex = /\[(.*?)\]/gm;
The /gm on the end just means it wont stop at the first one it finds and the "m" stands for multi-line matching.
The javascript string replace can accept both strings and regular expressions as the first argument. See the examples presented here.
In your case you are passing the first as a string of a regular expression: "\[(.*?)\]"
Instead you should either match the exact string sentence.replace("[Cole]", names[1]) or, what you probably want, is to use the regular expression to match any name sentence.replace(/\[.+\]/g, names[1]) (note that the first argument does not contain any quotes)
The /g (global) is used to match all occurrences in the sentence. Otherwise only the first occurrence would be replaced.
Could you try this :
function replacingText() {
var names = ["Cole", "Kyle", "Chase"];
var sentance = "This is [Cole] [ahmed]";
var regex = /\[([0-9]|[aA-zZ])*\]/g;
console.log(sentance.replace(regex, names[1]));
}
I just tried it and it works as expected

Regex replace all occurrences of text WITH brackets [duplicate]

This question already has answers here:
Javascript/regex: Remove text between square brackets
(4 answers)
Closed 5 months ago.
In short i need to replace every occurrence of text betweeen brackets including the brackets in a string, and the text to be replaced will be in a variable in Javascript.
A simple regex in a replace method wont work because of the brackets.
Example, replace "[test] [teste] test [hello]" with a variable with the value of "hi".
Output: "hi hi test [hello]"
"[test] [teste] test".replace(/\[.*?\]/g, 'hi')
escape the brackets with "\" and use g flag
edit: removed the i flag and chnaged w to . to handle anything inside brackets
I'm not quite sure what you're looking for but .match will store off the matches in an array and .replace will perform the replace for you.
const regex = /\[.*?\]/g;
var mutable = "[test] [teste] test";
const matches = mutable.match(regex); // Save all matches to an array
mutable = mutable.replace(regex, 'dude'); // Replace matches
console.log(mutable);
console.log(matches);
So, the way i found to do it was to get my variable to be replaced, example:
var test= "[test]",
Then i replaced the brackets in it so it would become "\[test\]", then i used:
var regex = new RegExp(test+"+","gm")
then i used this regex in JS replace method.

How to allow Forward Slash (/) in JavaScript Regex [duplicate]

This question already has answers here:
Escaping a forward slash in a regular expression
(6 answers)
Closed 8 years ago.
In my RadGrid I am using Filter for DATE Column. Date format is like this 16/12/1990. Filter textbox should allow only Numbers and /. How to write JavaScript function to do this?
function CharacterCheckDate(text, e)
{
var regx, flg;
regx = /[^0-9/'' ]/
flg = regx.test(text.value);
if (flg)
{
var val = text.value;
val = val.substr(0, (val.length) - 1)
text.value = val;
}
}
You don't have to worry about / in character class, (thanks Robin for pointing that out). For example,
console.log(/[^\d/]/.test("/"));
# false
console.log(/[^\d/]/.test("a"));
# true
If you are really in doubt, simply escape it with backslash, like this
regx = /[^0-9\/'' ]/
Also, you don't need to specify ' twice, once is enough.
regx = /[^0-9\/' ]/
Instead of using numbers explicitly, you can use \d character class, like this
regx = /[^\d\/' ]/
So, you could have written your RegEx, like this
regx = /[^\d/' ]/

Extract specific data from JavaScript .getAttribute() [duplicate]

This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed

Categories