I have a string like aman/gupta and I want to replace it to aman$$gupta and for that I am using JavaScript replace method as follows:
let a = "aman/gupta"
a = a.replace("/", "$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$$")
console.log(a) // 'aman$$gupta'
Why are the 1st and 2nd case identical and I get the expected result when I use $$$ instead of $$?
It’s because $$ inserts a literal "$".
So, you need to use:
a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"
See the following special 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 non-negative integer less than 100, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object.
$<Name>
Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., "$<Name>").
Also you can use split and join for better performance and $ isn't special for those functions.
var a = "aman/gupta"
a = a.split('/').join('$$')
alert(a); // "aman$$gupta"
To avoid the need to escape special characters you can use anonymous function as a replacer
a = "aman/gupta";
a = a.replace("/", function() {return "$$"});
console.log(a); // "aman$$gupta"
String.prototype.replace() documentation
Specifying a function as a parameter
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
The replace method provides replacement patterns that start with a dollar sign. One of them is $$ which inserts a single $. A single dollar sign in the replacement string will result in a literal one.
So if you want clean literal dollar signs, use $$ replacement patterns accordingly:
console.log('aman/gupta'.replace('/','$$')); // aman$gupta
console.log('aman/gupta'.replace('/','$$$$')); // aman$$gupta
console.log('aman/gupta'.replace('/','$$$$$$')); // aman$$$gupta
In regular expression replace with groups, if replacement is a variable, it needs to dollar sign escaped. Otherwise there will be bugs.
function escapeDollarSign(str) {
return str.replace(/\$/g, "$$$$")
}
Use below code its working for me.
var dollar = "$$$$";
console.log('abhishe/kadam'.replace('/', dollar.replace(new RegExp('\\$', 'g'), '$$$')));
Related
I have a string like this
var data = "{45}*[52]*{45}*[52]*{45}*[52]*69"
I need to replace all the square bracket & curly brackets to round brackets in javascript or jquery
I have tried this
.replace(/[\[\]']+/g,'')
but it replaces all the open and close brackets parallel
Expected result is = "(45)*(52)*(45)*(52)*(45)*(52)*69"
Any ideas ?
In a simple way you can use
"{45}*[52]*{45}*[52]*{45}*[52]*69".split(/[\{\[]/).join('(').split(/[\}\]]/).join(')')
You can call .replace() with a function as the second parameter.
With this function you can create a new substring which will be used as replacement.
str.replace(regexp|substr, newSubStr|function[, flags])
function (replacement)
A function to be invoked to create the new
substring (to put in place of the substring received from parameter
1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
Specifying a function as a parameter
You can specify a function as the second parameter. In this case, the
function will be invoked after the match has been performed. The
function's result (return value) will be used as the replacement
string. (Note: the above-mentioned special replacement patterns do not
apply in this case.) Note that the function will be invoked multiple
times for each full match to be replaced if the regular expression in
the first parameter is global.
"[abc]".replace(/\[|\]/g, function(m) {
var replacements = {"[": "(", "]": ")"}; return replacements[m];
});
in one replace
var data = "{45}*[52]*{45}*[52]*{45}*[52]*69";
data = data.replace(/[\[\{](\d+)[\]\}]/g, "($1)")
Though it will also replace [123} and {123] with (123) ... so not technically correct
if you want to only replace "correctly" formatted input, you need two replace calls
data = data.replace(/[\{](\d+)[\}]/g, "($1)").replace(/[\[](\d+)[\]]/g, "($1)")
I think
Try utilizing RegExp /(.\d{2}.)/ to match any character before two digits , two digits, any character ; .match() to match digits , return replacement string
var data = "{45}*[52]*{45}*[52]*{45}*[52]*69";
var res = data.replace(/(.\d{2}.)/g, function(match) {
return "(" + match.match(/\d+/)[0] + ")"
});
document.body.textContent = res;
I am trying to "intelligently" pre-fill a form, I want to prefill the firstname and lastname inputs based on a user email address, so for example,
jon.doe#email.com RETURNS Jon Doe
jon_doe#email.com RETURN Jon Doe
jon-doe#email.com RETURNS Jon Doe
I have managed to get the string before the #,
var email = letters.substr(0, letters.indexOf('#'));
But cant work out how to split() when the separator can be multiple values, I can do this,
email.split("_")
but how can I split on other email address valid special characters?
JavaScript's string split method can take a regex.
For example the following will split on ., -, and _.
"i-am_john.doe".split(/[.\-_]/)
Returning the following.
["i", "am", "john", "doe"]
You can use a regular expression for what you want to split on. You can for example split on anything that isn't a letter:
var parts = email.split(/[^A-Za-z]/);
Demo: http://jsfiddle.net/Guffa/xt3Lb9e6/
You can split a string using a regular expression. To match ., _ or -, you can use a character class, for example [.\-_]. The syntax for regular expressions in JavaScript is /expression/, so your example would look like:
email.split(/[\.\-_]/);
Note that the backslashes are to prevent . and - being interpreted as special characters. . is a special character class representing any character. In a character class, - can be used to specify ranges, such as [a-z].
If you require a dynamic list of characters to split on, you can build a regular expression using the RegExp constructor. For example:
var specialChars = ['.', '\\-', '_'];
var specialRegex = new RegExp('[' + specialChars.join('') + ']');
email.split(specialRegex);
More information on regular expressions in JavaScript can be found on MDN.
Regular Expressions --
email.split(/[_\.-]/)
This one matches (therefore splits at) any of (a character set, indicated by []) _, ., or -.
Here's a good resource for learning regular expressions: http://qntm.org/files/re/re.html
You can use regex to do it, just provide a list of the characters in square brackets and escape if necessary.
email.split("[_-\.]");
Is that what you mean?
You are correct that you need to use the split function.
Split function works by taking an argument to split the string on. Multiple values can be split via regular expression. For you usage, try something like
var re = /[\._\-]/;
var split = email.split(re, 2);
This should result in an array with two values, first/second name. The second argument is the number of elements returned.
I created a jsFiddle to show how this could be done :
function printName(email){
var name = email.split('#')[0];
// source : http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
var returnVal = name.split(/[._-]/g);
return returnVal;
}
http://jsfiddle.net/ts6nx9tt/1/
If you define your seperators, below code can return all alternatives for you.
var arr = ["_",".","-"];
var email = letters.substr(0, letters.indexOf('#'));
arr.map(function(val,index,rest){
var r = email.split(val);
if(r.length > 1){
return r.join(' ');
}
return "";
}
);
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+removeBrackets('$1')+'</noparse>');
This expression should be taking a string and encoding the parts wrapped in [noparse] tags so they don't render in a textarea.
I tested this as:
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
and:
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+String('$1')+'</noparse>');
and they work (without the desired effect).
function removeBrackets(input){
return input
.replace(/\[/g, '[')
.replace(/\]/g, '\');
}
What am I doing wrong in trying to pass the back reference into the removeBrackets function?
replace takes a function as callback and passes the capturing groups in the arguments:
var regex = /\[noparse\]([^\]]+)?\[\/noparse\]/ig;
string = string.replace(regex, function(_, match) {
return '<tag>'+ removeBrackets(match) +'</tag>';
});
The first param _ is the full string, unnecessary in most cases.
Your regular expression won't work, because of an error in the negative character set you're using. This fixes it:
input.replace(/\[noparse\]([^\[]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
^
Then, to perform the actual replacement, you need to pass a function as the second argument to .replace() instead of a simple string.
This question already has answers here:
Javascript string replace weirdness -- $$$$ gets collapsed to $$ -- what's the reason behind this result? [duplicate]
(3 answers)
`string.replace` weird behavior when using dollar sign ($) as replacement
(3 answers)
Closed 4 years ago.
I am trying to replace "this" in the below example with "$$Ashok".I am not getting expected output.
var adHtmltext ="this is ashok"
adHtmltext = adHtmltext.replace("this", "$$Ashok");
alert(adHtmltext );
why it is showing one $ in output? how to fix this?
Here is the jsfiddle http://jsfiddle.net/RxDa5/
Please help.
Have a look at the MDN documentation:
The replacement string can include the following special replacement patterns:
$$ Inserts a "$".
So you have to do:
adHtmltext.replace("this", "$$$$Ashok");
See also Javascript string replace weirdness -- $$$$ gets collapsed to $$ -- what's the reason behind this result?.
$$ is the escape code for $, since $ is the escape code for a regex backreference. Unfortunately, you need this:
var adHtmltext ="this is ashok"
adHtmltext = adHtmltext.replace("this", "$$$$Ashok");
alert(adHtmltext );
The dollar sign is a reserved character for .replace()
Indeed, in your jsFiddle code, right at the top, you've used it for it's reserved purpose -- ie the $1 that you've got in there to capture part of the expression.
$$ is used to escape a dollar sign. You need two dollar signs in this context for every single dollar sign you actually want.
This is because otherwise you couldn't have the string $1 in your output.
The .replace method will also accept regular expressions as the first argument, and if you group a portion of the text, you can include it in your output text with a "back-reference" using the '$' character and a number specifying which group to use ($1, $2, etc).
Because the '$' has a special meaning in this context, it needs to be escaped, and '$$' is the escape sequence to produce a normal '$', so you just need '$$$$Ashok' in your code.
There are special patterns that can be included in the string that you replace the target pattern with, and a string with '$$' is one of them. See the Mozilla MDN docs for a better reference.
In your case specifically, '$$' becomes '$' as certain combinations of other characters with '$', like '$&' are reserved for matching with certain substrings. If you want your replacement to work, just use '$$$$Ashok', which will become '$$Ashok' in the final string.
Any custom replacer function can solve this problem more elegantly. You just have to return the intended string from it and it will be replaced as it is.
function customReplacer() {
return "$$Ashok";
}
adHtmltext = adHtmltext.replace("this", customReplacer);
Looking for a generic solution, I obtained the following:
var input = prompt( 'Enter input:' ) || '';
var result = 'foo X bar X baz'.replace( /X/g, input.replace( /\$/g, '$$$$' ) );
It works:
input: $$
result: foo $$ bar $$ baz
input: $&
result: foo $& bar $& baz
But it's a bit tricky, because of the multi-level $ escaping. See that $$$$ in the inner replace...
So, I tried using a callback, to which special replacement patterns aren't applied:
var result = 'foo X bar X baz'.replace( /X/g, function () {
var input = prompt( 'Enter input:' ) || '';
return input;
} );
It works too, but has a caveat: the callback is executed for each replacement. So in the above example, the user is prompted twice...
Finally, here is the fixed code for the "callback" solution, by moving the prompt out of the replace callback:
var input = prompt( 'Enter input:' ) || '';
var result = 'foo X bar X baz'.replace( /X/g, function () {
return input;
} );
To summarize, you have two solutions:
Apply a .replace(/\$/g, '$$$$') escaping on the replacement string
Use a callback, which does nothing more than just returning the replacement string
MDN reference: String.prototype.replace()#Description
I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.
This question has been answered using Perl and PHP, but I can't get it to work in JavaScript. I've been trying this:
txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");
The pattern match works fine, but the replacement does not - the second part adds '~~' instead of the length of the pattern match. Putting the "$2" inside the parentheses doesn't work. What can I do to make it insert the right number of characters?
Use a function for replacement instead:
var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
return $1 + (new Array($2.length + 1).join("~")) + $3;
});
alert(txt);
//-> "==~~~~~=="
The issue with the expression
txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3")
is that "$2".length forces $2 to be taken as a string literal, namely the string "$2", that has length 2.
From the MDN docs:
Because we want to further transform the result of the match before the final substitution is made, we must use a function.
This forces evaluation of the match before the transformation.
With an inline function as parameter (and repeat) -- here $1, $2, $3 are local variables:
txt.replace(/(==)([^=]+)(==)/g, (_,$1,$2,$3) => $1+'~'.repeat($2.length)+$3);
txt = '==Hello==';
//inline function
console.log(
txt.replace(/(==)([^=]+)(==)/g, (_, g1, g2, g3) => g1 + '~'.repeat(g2.length) + g3)
);
The length attribute is being evaluated before the $2 substitution so replace() won't work. The function call suggested by Augustus should work, another approach would be using match() instead of replace().
Using match() without the /g, returns an array of match results which can be joined as you expect.
txt="==Hello==";
mat=txt.match(/(==)([^=]+)(==)/); // mat is now ["==Hello==","==","Hello","=="]
txt=mat[1]+Array(mat[2].length+1).join("~")+mat[3]; // txt is now "==~~~~~=="
You excluded the leading/trailing character from the middle expression, but if you want more flexibility you could use this and handle anything bracketed by the leading/trailing literals.
mat=txt.match(/(^==)(.+)(==$)/)
A working sample uses the following fragment:
var processed = original.replace(/(==)([^=]+)(==)/g, function(all, before, gone, after){
return before+Array(gone.length+1).join('~')+after;
});
The problem in your code was that you always measured the length of "$2" (always a string with two characters). By having the function you can measure the length of the matched part. See the documentation on replace for further examples.