If you try searching strings such as "[]" or "()" using the search() function it doesn't work.
function myFunction() {
var str = "Visit []W3Schools!";
var n = str.search("[]");
document.getElementById("demo").innerHTML = n;
}
You can try on W3Schools at -
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_search
Searching [] returns -1, while searching () returns 0. Always.
Why is that?
String.search uses a RegExp, and converts its argument to one if it isn't already. [] and () are special characters to RegExp.
You can directly create a regexp and escape the characters like so:
var n = str.search(/\[\]/);
But if you're searching for a literal string, then you should be using String.indexOf instead.
var n = str.indexOf("[]");
The JavaScript search function takes a regular expression as its argument:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
In regular expressions, "[" and "(" are special characters.
Try replacing your function with this:
function myFunction() {
var str = "Visit []W3Schools!";
var n = str.search("\\[]");
document.getElementById("demo").innerHTML = n;
}
or better:
var n = str.search(/\[]/);
The '[' special character is escaped. Once that is escaped, the ']' does not need to be escaped because it is only treated special after an unescaped '['.
For more information about regular expressions in JavaScript, look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
It's because search is expecting a regular expression. If a string is passed, then search will explicitly transform it into a regexp using new RegExp.
Calling it like str.search("[]") is like calling it str.search(/[]/) (nothing in the string matches an empty set so -1 is returned).
And calling it like str.search("()") is like calling it str.search(/()/) (the first empty string "" is found at the index 0).
I recommend looking for the docs on MDN not W3Schools.
Because the search string is a regular-expression and "[]" and "()" are both magic. You need to double-escape them:
str.search("\\[\\]")
Or even better, as ephemient points out:
str.indexOf("[]")
Related
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'), '$$$')));
I have a string as
pow((sin),(2))(4*x+5)+pow((cos),(3))(4*x+3)/pow((tan),(5))(x)
i need to get it as
pow(sin(4*x+5),2)+pow(cos(4*x+3),3)/pow(tan(x),5)
What i tried was
1)split the expression based on operators(+,-,/,*) between pow into single units.
2)extract expression between last parenthisis
3)Insert the extracted subexpression between first string after pow and first closing parenthis for all the units.
what i tried :-
re="pow((sin),(2))(4*x+5)+pow((cos),(3))(4*x+3)+pow((tan),(5))(x)";
re.split(+);
re.replaceAll("^[()]]{3}","\\(\\)]*\\)");
to be frank i am new to regular expression.
If your plan is to evaluate this, rather than lexically transform it, then you can do it by defining appropriate functions:
function pow(operator, exponent) {
return function(operand) {
return Math.pow(operator(operand), exponent);
};
}
var sin = Math.sin, cos = Math.cos, tan = Math.tan;
var x = 2;
> pow((sin),(2))(4*x+5)+pow((cos),(3))(4*x+3)/pow((tan),(5))(x)
< 0.17654033709528213
You can use following regex and replacement string:
Edited
Regular expression : ([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)
Replacement expression : $1($2($4),($3))$5
Check following code:
function cal()
{
var string = "pow((sin),(2))(4*x+5)+pow((cos),(3))(4*x+3)/pow((tan),(5))(x)";
var regex = /([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)/;
var replacement = "$1($2($4),($3))$5";
while(string.match(regex))
{
string = string.replace(regex,replacement);
}
alert(string);
}
cal();
I think regular expression is wrong tool for dealing with this. You may parse the expression in a loop and get the inner expression strings.
Restructure it the way you want and evaluate.
Parsing algorithm could be something like
Regular expression to detect semi-colon terminated C++ for & while loops
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.