JavaScript regex with escaped slashes does not replace - javascript

Do i have to escape slashes when putting them into regular expression?
myString = '/courses/test/user';
myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);
Instead of printing "test", it prints the whole source string.
See this demo:
http://jsbin.com/esaro3/2/edit

Your regex is perfect, and yes, you must escape slashes since JavaScript uses the slashes to indicate regexes.
However, the problem is that JavaScript's replace method does not perform an in-place replace. That is, it does not actually change the string -- it just gives you the result of the replace.
Try this:
myString = '/courses/test/user';
myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);
This sets myString to the replaced value.

/[\/]/g matches forward slashes.
/[\\]/g matches backward slashes.

Actually, you don't need to escape the slash when inside a character class as in one part of your example (i.e., [^\/]* is fine as just [^/]*). If it is outside of a character class (like with the rest of your example such as \/courses), then you do need to escape slashes.

string.replace doesn't modify the original string. Instead, a returns a new string that has had the replacement performed.
Try:
myString = '/courses/test/user';
document.write(myString.replace(/\/courses\/([^\/]*)\/.*/, "$1"));

Note, that you don't have to escape / if you use new RegExp() constructor:
console.log(new RegExp("a/b").test("a/b"))

Related

why does this js RegExp test return true? [duplicate]

The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'
this is the expression
[\s\/\)\(\w&-]
I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?
var programProductRegex = new RegExp([\s\/\)\(\w&-]);
You can use the regular expression syntax:
var programProductRegex = /[\s\/\)\(\w&-]/;
You use forward slashes to delimit the regex pattern.
If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:
var programProductRegex = new RegExp("[\\s\\/\\)\\(\\w&-]");
All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.
Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.
var programProductRegex = new RegExp(userInput);
If you are using a String and want to escape characters like (, you need to write \\( (meaning writing backslash, then the opening parenthesis => escaping it).
If you are using the RegExp object, you only need one backslash for each character (like \()
Enclose your regex with delimiters:
var programProductRegex = /[\s\/)(\w&-]/;

javascript check if string contains any symbols

I have the following set of symbols:
var a = '|\/~^:,;?!&%$#*+';
How can I check is the following string contains any of those symbols?
var b = 'avguybdf';
As suggested, regular expressions will work.
b.match(/[|\\/~^:,;?!&%$#*+]/);
EDIT: I originally used the method here https://stackoverflow.com/a/6969486/2044733 to escape the string but because of the grouping, only the backslash character needs to be escaped.
The "/" at the beginning and end of the string are the delimiters for regular expressions in javascript, and "[]" are used to group the characters. In case you're wondering how this works.
Use RegEx
Check the how to use regex # Javascript RegEx
Try one of the following examples that use regular expressions:
http://www.webdeveloper.com/forum/showthread.php?264705-Best-way-to-check-for-multiple-characters-in-a-string
http://tjvantoll.com/2013/03/14/better-ways-of-comparing-a-javascript-string-to-multiple-values/
Use RegEx. You can use test() or exec(). Read more here: http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Different in Convert Regular Expression String to RegExp in Javascript

Why isn't my code around the test function in Object RegExp working the same way as the regex pattern. Am I missing something or Am I using the wrong escape regex
<html>
<body>
<script type="text/javascript">
var str = "info#test.com";
//This isn't working
var regStr = "^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$"; //This string can be any regex get from XSLT
//Escape function get from: http://stackoverflow.com/a/6969486/193850
regStr = regStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
console.log(regStr); // \^\(\[w\-\]\+\(\?:\.\[w\-\]\+\)\*\)#\(\(\?:\[w\-\]\+\.\)\*w\[w\-\]\{0,66\}\)\.\(\[a\-z\]\{2,6\}\(\?:\.\[a\-z\]\{2\}\)\?\)\$
var re = new RegExp(regStr , "i");
console.log(re.test(str)); //false
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
console.log(filter.test(str)); //true
</script>
</body>
</html>
You have to double your backslashes when you write a regular expression as a string.
Why? The string literal syntax also observes its own backslash-quoting convention, for things like quote characters, newlines, etc. Therefore, when JavaScript parses your string constant that contains the regular expression, the backslashes will disappear. Thus, you need to quote them with another backslash so that when you pass the string to the RegExp constructor it sees the regular expression you actually intended.
See, there's a confusion. The function you've used is a nice way of preprocessing your string-to-be regexes so you don't have to worry about escaping regex metacharacters - i.e., symbols that will control the regex behaviour, and not just taken literally.
But the point is that your string has already been parsed before it was taken by this escaping function: \w and \. sequences became just w and . respectively, the preceding slash was lost.
For characters not listed in Table 2.1, a preceding backslash is
ignored, but this usage is deprecated and should be avoided.
The escaper function, actually, did restore the slash before the ., but w wasn't special for it in any kind. ) Therefore the string that went into RegExp constructor had [w] instead of [\w].
It's actually quite easy to check: just console.log(regStr) after the replacement operation.

jQuery - Replace all parentheses in a string

I tried this:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace("(", "").replace(")", "");
It works for all double and single quotes but for parentheses, this only replaces the first parenthesis in the string.
How can I make it work to replace all parentheses in the string using JavaScript? Or replace all special characters in a string?
Try the following:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
A little bit of REGEX to grab those pesky parentheses.
You should use something more like this:
mystring = mystring.replace(/["'()]/g,"");
The reason it wasn't working for the others is because you forgot the "global" argument (g)
note that [...] is a character class. anything between those brackets is replaced.
You should be able to do this in a single replace statement.
mystring = mystring.replace(/["'\(\)]/g, "");
If you're trying to replace all special characters you might want to use a pattern like this.
mystring = mystring.replace(/\W/g, "");
Which will replace any non-word character.
You can also use a regular experession if you're looking for parenthesis, you just need to escape them.
mystring = mystring.replace(/\(|\)/g, '');
This will remove all ( and ) in the entire string.
Just one replace will do:
"\"a(b)c'd{e}f[g]".replace(/[\(\)\[\]{}'"]/g,"")
That should work :
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
That's because to replace multiple occurrences you must use a regex as the search string where you are using a string literal. As you have found searching by strings will only replace the first occurrence.
The string-based replace method will not replace globally. As such, you probably want to use the regex-based replacing method. It should be noted:
You need to escape ( and ) as they are used for group matching:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
This can solve the problem:
myString = myString.replace(/\"|\'|\(|\)/)
Example

Brackets in Regular Expression

I'd like to compare 2 strings with each other, but I got a little problem with the Brackets.
The String I want to seek looks like this:
CAPPL:LOCAL.L_hk[1].vorlauftemp_soll
Quoting those to bracket is seemingly useless.
I tried it with this code
var regex = new RegExp("CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll","gi");
var value = "CAPPL:LOCAL.L_hk[1].vorlauftemp_soll";
regex.test(value);
Somebody who can help me??
It is useless because you're using string. You need to escape the backslashes as well:
var regex = new RegExp("CAPPL:LOCAL.L_hk\\[1\\].vorlauftemp_soll","gi");
Or use a regex literal:
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi
Unknown escape characters are ignored in JavaScript, so "\[" results in the same string as "[".
In value, you have (1) instead of [1]. So if you expect the regular expression to match and it doesn't, it because of that.
Another problem is that you're using "" in your expression. In order to write regular expression in JavaScript, use /.../g instead of "...".
You may also want to escape the dot in your expression. . means "any character that is not a line break". You, on the other hand, wants the dot to be matched literally: \..
You are generating a regular expression (in which [ is a special character that can be escaped with \) using a string (in which \ is a special character).
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi;

Categories

Resources