Parsing regex in javascript [duplicate] - javascript

This question already has answers here:
JavaScript Regex, where to use escape characters?
(3 answers)
Closed 8 years ago.
I'm unable to parse a regex. I've tested it from regexpal.com and regex101.com (by setting the expression as "(?:^csrf-token|;\s*csrf-token)=(.*?)(?:;|$)" and the test string as "__ngDebug=false; csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj") where it works.
The example is jsfiddle.
function getCookie(name) {
var s = "__ngDebug=false; csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj";
var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
var result = regexp.exec(s);
return (result === null) ? null : result[1];
}
alert(getCookie("csrf-token"));
If however s is "csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj", then it works fine. Please tell me what's wrong.
The expected output is "b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj", and there is no input (the string to be tested is 's').

Change
"|;\s*"
to
"|;\\s*"
^
The thing is, you are constructing the RegExp by passing in a string via the constructor, so you need to follow the rule of escaping in string literal. In JavaScript, "\s" is recognized as a single character string, with lowercase s. To specify \, you need to escape it.

You should escape \s
var regexp = new RegExp("(?:^" + "csrf-token" + "|;\\s*"+ "csrf-token" + ")=(.*?)(?:;|$)", "g");
^

Related

Replacing only exact matches in Regex [duplicate]

This question already has answers here:
How can I match a whole word in JavaScript?
(4 answers)
Closed 4 months ago.
I have a javascript function that replaces strings that match against a profanity library with symbols.
eg. damn is transformed into ##$%&!
However, this replace is non-discriminating, and will transform partial matches as well.
eg. classic is transformed into cl##$%&!ic
I'm very new to TS/JS and Regex and would like some help understanding this function's arguments and how to modify them for only exact matches.
this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
To avoid partial matches, the normal solution is to surround what you want to match with word boundaries \b.
The following example assumes that profanities does not contain any words that contain regex special characters.
Notice that the "shit" in "mishit" and the "ass" in "class" do not get replaced.
const profanities = ['damn', 'shit', 'ass'];
// As regex literal: /\b(?:damn|shit|ass)\b/
const re = new RegExp('\\b(?:' + profanities.join('|') + ')\\b', 'gi');
const text = "Damn, another mishit. I am shit at pool. Time to get my ass to class.";
console.log(text.replace(re, '##$%&!'));

No \p{L} for JavaScript Regex ? Use Unicode in JS regex [duplicate]

This question already has answers here:
Preg_match to regex equivalent expression to match any Unicode letters
(2 answers)
Match only unicode letters
(3 answers)
Closed 4 years ago.
I nedd to add a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ x time but I find this very ugly. So I try \p{L} but it does not working in JavaScript.
Any Idea ?
my actual regex : [a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ][a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ' ,"-]*[a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ'",]+
I want to have a thing like that : [\p{L}][\p{L}' ,"-]*[\p{L}'",]+ (or smaller than the actual expression)
What you need to add is a subset of what you asked for. First you should define what set of characters you need. \pL means every letter from every language.
It's kind of ugly but doesn't affect performance and rather the best solution to get around such kind of problems in JS. ECMA2018 has a support for \pL but way far to be implemented by all major browsers.
If it's a personal taste, you could reduce this ugliness a bit:
var characterSet = 'a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ';
var re = new RegExp('[' + characterSet + ']' + '[' + characterSet + '\' ,"-]*' + '[' + characterSet + '\'",]+');
This update credits go to #Francesco:
var pCL = 'a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ';
var re = new RegExp(`[${pCL}][${pCL}' ,"-]*[${pCL}'",]+`);
console.log(re.source);
You have XRegExp addon to support unicode letter matcher:
var unicodeWord = XRegExp("^\\pL+$"); // L: Letter
Here you can see more example matching unicode in javascript
http://xregexp.com/plugins/

Regex that detects greater than ">" and less than "<" in a string [duplicate]

This question already has answers here:
Regular expression greater than and less than
(3 answers)
Closed 8 years ago.
I need a regular expression that replaces the greater than and less than symbol on a string
i already tried
var regEx = "s/</</g;s/>/>/g"
var testString = "<test>"
alert(testString.replace(regEx,"*"))
My first time to use it please go easy on me :)
Thanks
You can use regEx | like
var regEx = /<|>/g;
var testString = "<test>"
alert(testString.replace(regEx,"*"))
Fiddle
For greater than and less than symbol.
var string = '<><>';
string = string.replace(/[\<\>]/g,'*');
alert(string);
For special characters
var string = '<><>';
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
alert(string);
Insert the regular expression in the code before class
using System.Text.RegularExpressions;
below is the code for string replace using regex
string input = "Dot > Not Perls";
// Use Regex.Replace to replace the pattern in the input.
string output = Regex.Replace(input, "some string", ">");
source :
http://www.dotnetperls.com/regex-replace

Remove '=' character from a string [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I have a string as follows:
var string = "=09e8d76c-c54c-32e1-a98e-7e654d32ec1f";
How do I remove the '=' character from this? I've tried a couple of different ways but the '=' character seems to be causing a conflict
If it's always the first character then this will work...
var string = "=09e8d76c-c54c-32e1-a98e-7e654d32ec1f".substring(1);
If it's not definitely the first character then this will work...
var string = "=09e8d76c-c54c-32e1-a98e-7e654d32ec1f".replace("=", "");
If it's in there more than once then this will work...
var string = "=09e8d76c-c54c-32e1-a98e-7e654d32ec1f".split("=").join("");
You can use .replace():
The replace() method returns a new string with some or all matches of
a pattern replaced by a replacement
string = string.replace('=','');
Fiddle Demo
Its very simple.
var string = "=09e8d76c-c54c-32e1-a98e-7e654d32ec1f";
string=string.replace('=','');
To get rid of the first character:
string = string.substring(1);
Do this:
var string = "=09e8d76c-c54c-32e1-a98e-7e654d32ec1f";
if(string.indexOf('=')>=0){ //check string contains =
string = string.replace("=",'');
}

How can I replace '/' in a Javascript string with another character [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript replace all / with \ in a string?
I have a date='13/12/2010' I want to replace this '/' to '_' or something else.
I read this But I do not know how can that applied for my case .
Use a global RegEx (g = global = replace all occurrences) for replace.
date = date.replace(/\//g, '_');
\/ is the escaped form of /. This is required, because otherwise the // will be interpreted as a comment. Have a look at the syntax highlighting:
date = date.replace(///g, '_');
One easiest thing :)
var date='13/12/2010';
alert(date.split("/").join("_")); // alerts 13_12_2010
This method doesn't invoke regular expression engine and most efficient one
You can try escaping the / character like this -
date.replace( /\//g,"_");

Categories

Resources