Replace All Occurrences Of a String in JavaScript - javascript

I have a string as follows
var company = "Microst+Apple+Google";
And I want replace all the + signs with %2B
But when I use this code. It returns 0
var company = company.replace(/+/g, "%2B");
I think JavaScript thinks that + is an arithmetic operation. Is there a special symbol to be used? or can user a variable except directly using the + sign?
If so please mention. Any Idea how to do this ?

You need escape it :
var company = company.replace(/\+/g, "%2B");
It is because + is special symbol used to indicate that preceding character should match 1 or more times.
You can read more about regular expressions syntax here: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

No, JavaScript doesn't think it's an arithmetic operation but + is a quantifier in regular expressions and the regular expression parser doesn't understand yours.
You must escape the + :
var company = company.replace(/\+/g, "%2B");

You can use this :
var company = company.replace(/\+/g, "%2B");
Or an easier way :
var company = encodeURIComponent(company);
which will do the same operation as the regex one. Also, it encodes all URI chars like &, " (quotes), % etc... if there is one like it in the string given.
In both cases, the output is :
Microst%2BApple%2BGoogle

Related

Javascript: Difference in Regex String and Regex [duplicate]

This question already has answers here:
Differences between Javascript regexp literal and constructor
(2 answers)
Closed 7 years ago.
I have to put a given variable into a regular expression. When I do it with hard coded data it works. Here is my code for that
/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!ccarn).)*$/
This should ( and does ) look for a word (password in this case) that is case sensitive, has at least one capitol and one lowercase letter, and one number or symbol. It cannot, however, contain the word "ccarn" in it. Again when I put this in as my regex all works out. When I try to turn it into a string that gets passed in, it doesn't work. Here is my code for that
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');
I feel like I may just be missing something in translation/transition, but can't seem to get it right. TIA
When you use the new RegExp() constructor to construct a regex from a string, you shouldn't include the leading and trailing / within the string. The /.../ form is only to be used when specifying a regex literal, which isn't what you're doing here.
When you do, say, var r = new RegExp('/foo/'), the regex you're actually getting is equivalent to doing var r = /\/foo\//, which clearly isn't what you want. So your constructor should actually look like this:
var regex = new RegExp('^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$');
// ↑↑ ↑↑
// no "/" at the locations pointed to above
You probably also need to double your backslashes (since backslashes are escape characters in strings, but not in regex literals). So, [0-9##$-/:-?{-~!"^_`\[\]] needs to become [0-9##$-/:-?{-~!"^_`\\[\\]].
If you look closely the '/' character gets delimited when you give it inside the quotes so essentially the
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');
The regular expression would be like this
/\/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-\/:-?{-~!"^_`[]])+((?!ccarn).)*$\//
The right way to go is to remove the '/' character from the RegEx and it should work
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');
The output for the above would be
/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-\/:-?{-~!"^_`[]])+((?!ccarn).)*$/
which is exactly what you need ?
Hope it helps
Please before doing anything else, read a regex tutorial!
Mistakes:
A lookahead is a zero width assertion ( in other words, it's only a test and doesn't match anything ), putting a quantifier for a zero width assertion doesn't make any sense: (?=.*[a-z])+ (it is like repeating something empty, zero or more times. Note that the regex engine will protest if you write something like this.)
When you use the oop syntax to define a pattern (ie:var pattern = new RegExp("...), you don't need to add delimiters. You need to put double backslashes instead simple backslashes.

Check if string contains a regex & no js

I have a string and I need to make sure that it contains only a regular expression and no javascript because I'm creating a new script with the string so a javascript snippet would be a security risk.
Exact scenario:
JS in mozilla addon loads configuration as json through HTTPrequest (json contains {"something": "^(?:http|https)://(?:.*)"}
JS creates a pac file(proxy configuration script) that uses the "something" regex from the configuration
Any ideas how to escape the string without destroying the regex in it?
It seems that most of the standard JavaScript functionality is available (source), so you can just do:
try {
RegExp(json.something+'');
pacFile += 'RegExp(' + JSON.stringify(json.something+'') + ')';
} catch(e) {/*handle invalid regexp*/}
And not worry, because a RegExp("console.log('test')") will only produce a valid /console.log('test')/ regexp and execute nothing.
You can use a regular expression to pull apart a JavaScript regular expression.
Then you should convert the regex to a lexically simpler subset of JavaScript that avoids all the non-context-free weirdness about what / means, and any irregularities in the input regex.
var REGEXP_PARTS = "(?:"
// A regular character
+ "[^/\r\n\u2028\u2029\\[\\\\]"
// An escaped character, charset reference or backreference
+ "|\\\\[^\r\n\u2028\u2029]"
// A character set
+ "|\\[(?!\\])(?:[^\\]\\\\]|\\\\[^\r\n\u2028\u2029])+\\]"
+ ")";
var REGEXP_REGEXP = new RegExp(
// A regex starts with a slash
"^[/]"
// It cannot be lexically ambiguous with a line or block comemnt
+ "(?![*/])"
// Capture the body in group 1
+ "(" + REGEXP_PARTS + "+)"
// The body is terminated by a slash
+ "[/]"
// Capture the flags in group 2
+ "([gmi]{0,3})$");
var match = myString.match(REGEXP_REGEXP);
if (match) {
var ctorExpression =
"(new RegExp("
// JSON.stringify escapes special chars in the body, so will
// preserve token boundaries.
+ JSON.stringify(match[1])
+ "," + JSON.stringify(match[2])
+ "))";
alert(ctorExpression);
}
which will result in an expression that is in a well-understood subset of JavaScript.
The complex regex above is not in the TCB. The only part that needs to function correctly for security to hold is the ctorExpression including the use of JSON.stringify.

Splitting a string at special character with JavaScript

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 "";
}
);

Dynamics Pattern Javascript

I got request on a remote service, this service give me fields with patterns as follows:
[a-zA-Zа-яА-ЯёЁ'+-]{1,100}
[0-9a-zA-Zа-яА-ЯёЁ'+-]{2,10}
In square bracket contains allowed symbols.
In curly brackets contains minimal and maximum symbols.
So I have fields and their patterns.
How I can validate entered data by incoming pattern?
Send the string to the RegExp constructor and use test.
For example:
string = "[a-zA-Zа-яА-ЯёЁ'+-]{1,100}"
pattern = new RegExp(string)
alert(pattern.test("This works, привет, 123"));
alert(pattern.test("$☛☛"));
Live demo
Depending on your situation, you might want to add "^" and "$" to the pattern.
You should use JavaScript regular expression to solve this.
you can do like this
"some test".match(/[a-zA-Zа-яА-ЯёЁ'+-]{1,100}/)
which returns ["some"]
or
/[a-zA-Zа-яА-ЯёЁ'+-]{1,100}/.test("some test")
which returns true
A simple example:
var s = "hello123";
var r1 = "[a-zA-Zа-яА-ЯёЁ'+-]{1,100}"; // the pattern you were given
var reg1 = RegExp("^" + r1 + "$"); // the pattern enclosed in `^` `$`
var r2 = "[0-9a-zA-Zа-яА-ЯёЁ'+-]{2,10}";
var reg2 = RegExp("^" + r2 + "$");
alert(reg1.test(s)); // false
alert(reg2.test(s)); // true
The regular expression has the pattern you mentioned, but enclosed between ^ and $ - meaning "the whole expression". The first expression fails because there is a number in s which is not allowed. The second expression passes - it has only numbers and letters, and between 2 and 10 characters total.

Regular expression to replace spaces with dashes

I'm trying to work out what regular expression I would need to take a value and replace spaces with a dash (in Javascript)?
So say if I had North America, it would return me North-America ?
Can I do something like var foo = bar.replace(' ', '-') ?
It's better to use:
var string = "find this and find that".replace(/find/g, "found");
to replace all occurrences.
The best source of information for regular expressions in various languages that I've found is Regular-Expressions.info (and I linked directly to the Javascript section there).
As for your particular question, yes, you can do something like that. Did you try it?
var before = 'North America';
var after = before.replace(/ +/g, '-')
alert('"' + before + '" becomes "' + after + '"');
Use the site I showed you to analyze the regex above. Note how it replaces one or more spaces with a single hyphen, as you requested.
For the most regular expressions, you can do it by testing with the regular expression tester.

Categories