How to use RegEx with a variable for replacing [duplicate] - javascript

This question already has answers here:
Javascript Regex: How to put a variable inside a regular expression? [duplicate]
(9 answers)
Closed 4 years ago.
My title might not be worded correctly sorry in advance.
I've looked everywhere and I honestly can't seem to figure it out.
I want to use a variable in a RegEx but the solution that i've found and tried to work off of works but it is not flexible for what I need. I can't seem to figure out how to convert it to a RegEx constructor object which I think is my best bet. Any help will be greatly appreciated.
let str = 'haeandviaecy'
let newString = str.replace(/(\w{3})/g, '$1 ').replace(/(^\s+|\s+$)/, '')
//hae and via ecy
replace(/(^\s+|\s+$)/,'') removes any preceding or trailing space from the string - just giving you a heads up
So what this snippet does is go to every third and put a blank space in it. What I want is to make my code more flexible and be able to put a variable to let me choose the number for when it puts a blank space using a variable.
right now it prints out - "hae and via ecy"
for ex. every 4th would be - haea ndvi aecy
I've read you cant put in variables unless it is a RegEx contructor object. When I've tried to convert it doesn't seem to work.

If gather the question correctly, you can use a template literal as parameter passed to RegExp constructor.

Related

Am confused about the functions of caret(^) in Regular expresssions. What does it mean here [^'] and what does it mean here [^01] [duplicate]

This question already has answers here:
Negating specific characters in regex
(4 answers)
Reference - What does this regex mean?
(1 answer)
Closed 20 days ago.
I have a regular expression:
/'([^']*)'/
Am finding it hard to understand how it works. The function of the caret here confuses me.
Unlike this regex:
/[^01]/ : i understand the caret here is an inverter which means the search should return true for any input input value that is different from 01.
let quotedText = /'([^']*)'/;
console.log(quotedText.exec("She said 'hello'"));
The console: ["'hello'", "hello"]
I do understand how the regexpression(quotedText) finds hello. What if the statement was longer with more words in quote. Like:
("She said 'hello' and he responded 'Hi', 'do you need my help'").
Would the exec method find all the words or sentences in quotes?.
I am also very confused about the function of caret^ here. Is it inverting?? Or is it showing where the exec methods starts looking from. Whats the difference between [^']* and [^01]. Does the function of caret change based on the method. Does caret(^) you see work differently when used with test method or exec method?. does Caret behave differently when in square brackets?

Create regex object using string input [duplicate]

This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 4 years ago.
I have a regex when I instantiate the Regex object like this:
this.checkRegex = new RegExp(/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/);
It works fine, however If I store the regex in string it does not work:
private checkReg: string = '/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/';
this.checkRegex = new RegExp(this.checkReg);
I am using angular-typescript. What is the thing I am missing here when I am trying to instantiate by throwing string inside the constructor. Code sample will be really appreciated. Thanks for your help.
When you are passing a string to the RegExp constructor, you need to change it a little bit. Instead of
'/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/'
You would omit the preceding and trailing slash
'^([0|\\[+][0-9]{0,5})?([1-9][0-9]{0,15})$'
Note also double escaping the back slash.
If you want to store the RegExp as a String, store it without the forward slashes at the front and back. When creating the RegExp object, those get escaped:
new RegExp('/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/');
will result in
/\/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$\//
while,
new RegExp('^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$');
will work:
/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$/

JS Substrings understanding? [duplicate]

This question already has answers here:
Why are slice and range upper-bound exclusive?
(6 answers)
Closed 9 years ago.
I'm on Codecademy and I am learning JavaScript. I'm on substrings and I get how to do them, but I wander why substrings extracts characters from indexA up to but not including indexB. Why does it include indexA, but only up to indexB?
Please use the best layman's term for this, considering I don't have that much knowledge in this language (I'm only familiar with HTML & CSS).
var longString = "this is a long string";
var substr1 = longString.substring(0, 4); //"this"
var substr2 = longString.substring(4, 8); //" is "
This makes sense because the second substring started from where the first left off, without copying the same letter twice in both substrings. It makes it more useful in loops, for example.
Also, as everyone keeps pointing out, because "it's defined that way..."
That's because it's designed that way. Here's some documentation from MDN.
"Hello World".substring(0,5) //Hello
Simply saying
Get the substring starting with (and including) the character at the first index, and ending (but not including) the character at the second index.
Well, the method is defined in that way. Extracts from indexA up to indexB but not including.
In Javascript there are two different functions to extract a substring. One with length and other with index start and stop.
String.substring( from [, to ] )
String.substr( start [, length ] )
In all cases, the second argument is optional. If it is not provided, the substring will consist of the start index all the way through the end of the string.
Please go through this article to clear up.
http://www.bennadel.com/blog/2159-Using-Slice-Substring-And-Substr-In-Javascript.htm

RegEx: Extract GET variable from URL [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something&notinteresting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something&notinteresting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something&notinteresting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.

javascript replace query string value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
add or update query string parameter
I am trying to replace the page number in the query string no matter what digit is to 1.
query string
index.php?list&page=2&sort=epub
javascript
window.location.href.replace(new RegExp("/page=.*?&/"), "page=1&")
Your code looks almost right; however:
you need to use either new RegExp or the special // regex syntax, but not both.
the replace method doesn't modify the string in-place, it merely returns a modified copy.
rather than .*?, I think it makes more sense to write \d+; more-precise regexes are generally less likely to go awry in cases you haven't thought of.
So, putting it together:
window.location.href = window.location.href.replace(/page=\d+/, "page=1");

Categories