I have a string like this :
whatever/aaazzzzz
and sometimes a string like that :
whatever\bbbbzzzzz
I would like to split the string when I match / or \
The regex I tried seems to work
https://regex101.com/r/gP5gL0/1
When I use it in the fiddle, it works with / but not with \
Any ideas?
The issue here is not the regex itself, but the unavoidable fact that JavaScript doesn't implicitly support string literals (i.e. ones where backslashes are interpreted as printed as opposed to denoting an escape sequence. Much more can read here).
Strings derived from any source other than source code are interpreted as literal by default, as demonstrated in this fiddle.
<script>
function splitTheString()
{
//test = escape("whatever\aaaaaa");
var test = document.getElementById("strToSplit").value;
a = test.split(/(\\|\/)/)[0];
alert(a);
}
</script>
<form>
Split this string:<br>
<input type="text" id="strToSplit">
Split the string
</form>
Use this
var arr = str.split(/[\\|\/]/);
var str = 'whatever\\bbbbzzzzz';
alert(str.split(/[\\|\/]/))
Related
var str='\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf';
var res=str.replace('\E', '');
I am getting return like this:
\E.1.2.154EcsE877_P9999_Adult{2}_02_05_2019_0329p.pdf
I need to replace all '\E' from string and expecting output like this (\\10.1.2.154\bcs\30877_P9999_Adult{2}_02_05_2019_0329p.pdf). Some body please advise on this . I tried to do several way to fix this. No luck. When I tried with C# it's working fine.
static void Main(string[] args)
{
string str=#"\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf";
str=str.Replace(#"\E","");
Console.WriteLine(str);
Console.Read();
}
But, I need it in JavaScript.
var str='\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf';
var res=str.replace(/\\E/g, '');
console.log(str, res)
You must use RegExg to eliminate the escape inside a string in JavaScript.
In JavaScript the equivalent of the C# # prefix is String.raw followed by a template literal (notice the backtics).
And to replace all occurrences, not just one, you need to pass a regex to replace with g modifier.
var str=String.raw`\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf`;
var res=str.replace(/\\E/g, '');
console.log(res);
NB: The backslash in a regular expression is an escape character, so you need \\ for one literal backslash.
If for some reason you really want to avoid the use of a regex, then there is the split/join trick, but it is a bit slower:
var str=String.raw`\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf`;
var res=str.split(String.raw`\E`).join('');
console.log(res);
Older JS engines
For older JS engines that do not support String.raw you need to use standard string literals, which use the backslash as escape character. So then you need to double all of them. But this is only needed when you write the string as a literal. When you get the string via some API, then there is no need to alter the string before doing the replacement:
var str='\\E\\\\E\\10.1.2.154\\E\\bcs\\E\\30877_P9999_Adult{2}_02_05_2019_0329p.pdf';
var res=str.replace(/\\E/g, '');
console.log(res);
How to declare associative array of regex?
This is not working
var Validators = {
url : /^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm
};
EDITED: Now working!
This will be valid in JS (like # operator in C#)
url : `/^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm`
However, will still not work due to double escape, one in JS and other in Regex. If expression is small, perhaps naked eye can manually escape for both JS and Regex. My brain just can't :)
In order to use strings as tested on regex101.com for example, all required strings should be declared as 'row' like this:
var exp = String.raw`^(http(s?):\/\/)?(((www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$`;
var strings = [
String.raw`http://www.goo gle.com`,
String.raw`http://www.google.com`,
];
Wrap it with new RegExp() and escape slashes
var Validators = {
url : new RegExp( /^http(s?):\/\/((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(\/)?$/gm )
};
Your regex has forward slashes in it. This symbol needs to be escaped because it is supposed to indicate the start and end of the expression. Try \/.
Look at this simple HTML input tag:
<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex'
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />
<p id='log'></p>
Now imagine that we want to validate this field, using this function:
var log = $('#log');
function validateRegex(field) {
var pattern = field.attr('data-validation-regex-pattern');
log.append(pattern + '<br />');
if (pattern && pattern != '') {
var isValid = new RegExp(pattern).test(field.val().trim());
if (!isValid) {
log.append('not valid<br />');
}
else {
log.text('valid<br />');
}
}
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());
Now, if you look at the log, you see that this line returns false:
var isValid = new RegExp(pattern).test(field.val().trim());
However, this line of code returns true:
new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());
In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.
Why? What's wrong here?
To see it in action, look at this fiddle.
Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:
data-validation-regex-pattern='^\+\d{2}\.\d{10}$'
Will work just fine:
Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/
\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.
Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).
To get your code work, replace double slashes (\\) in your HTML by a single slash.Fiddle: http://jsfiddle.net/GRL2m/5/
Extra information:
In HTML, HTML entities (eg ") are used to display special characters.
In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.
Im using this snippet to replace several characters in a string.
var badwords = eval("/foo|bar|baz/ig");
var text="foo the bar!";
document.write(text.replace(badwords, "***"));
But one of the characters I want to replace is '/'. I assume it's not working because it's a reserved character in regular expressions, but how can I get it done then?
Thanks!
You simply escape the "reserved" char in your RegExp:
var re = /abc\/def/;
You are probably having trouble with that because you are, for some reason, using a string as your RegExp and then evaling it...so odd.
var badwords = /foo|bar|baz/ig;
is all you need.
If you INISIST on using a string, then you have to escape your escape:
var badwords = eval( "/foo|ba\\/r|baz/ig" );
This gets a backslash through the JS interpreter to make it to the RegExp engine.
first of DON'T USE EVAL it's the most evil function ever and fully unnecessary here
var badwords = /foo|bar|baz/ig;
works just as well (or use the new RegExp("foo|bar|baz","ig"); constructor)
and when you want to have a / in the regex and a \ before the character you want to escape
var badwords = /\/foo|bar|baz/ig;
//or
var badwords = new RegExp("\\/foo|bar|baz","ig");//double escape to escape the backslash in the string like one has to do in java
I have posted a problem in the above link - regExpression.test.
Based on that I have done like bellow that also produces an error.
var regExpression=new RegExp("^([a-zA-Z0-9_\-\.]+)$");
alert (regExpression.test("11aa"));
You need to escape your \ since you're declaring it with a string, like this:
var regExpression=new RegExp("^([a-zA-Z0-9_\\-\\.]+)$");
^ ^ add these
You can test it here.
You can also use the literal RegExp syntax /…/:
var regExpression = /^([a-zA-Z0-9_\-\.]+)$/;
By the way: The . does not need to be escaped in character classes anyway. And if you put the range operator at the begin or the end of the character class or immediately after a character range, it doesn’t need to be escaped either:
var regExpression = /^([a-zA-Z0-9_.-]+)$/;