This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 2 years ago.
I’m trying to use a variable in a RegEx and I’m having problems. This is my function:
const truncateNum = (num, place = 2) => {
const matcher = `/^-?\d+(?:\.\d{0,${place}})?/`;
const re = new RegExp(matcher);
return num.toString().match(re)[0];
};
When running this I get the following error:
Uncaught TypeError: Cannot read property '0' of null
What am I doing wrong here?
There are a few issues with your code.
The first is that when you define a regex as a string, it doesn't require // marks, and also backslashes need to be double escaped \\d+.
The second is that num.toString().match(re) will return null if the regular expression doesn't match, thus you are getting an exception from trying to do an array lookup on null[0].
let truncateNum = (num, place = 2) => {
const matcher = `^-?\\d+(?:\\.\\d{0,${place}})?`; console.log(matcher);
const re = new RegExp(matcher);
const match = num.toString().match(re);
const result = match && match[0] || '0'
return result;
};
Related
This question already has answers here:
Regex to find or extract strings between the "<>" angle brackets
(3 answers)
Find substring between angle brackets using jQuery
(3 answers)
Regex to get string between curly braces
(16 answers)
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 months ago.
How can implement a function that returns a list of characters between two characters?
const string = "My name is <<firstname>> and I am <<age>>";
const getVariables = (string) => {
// How do I implement?
}
console.log(getVariables(string)); // ['firstname', 'age']
PS: I realize there are multiple answers on how to do something similar, but all of them only work for getting first instance and not all occurrences.
Assuming this is some kind of templating, you can proceed like this:
let format = (str, vars) =>
str.replace(/<<(\w+)>>/g, (_, w) => vars[w]);
//
const tpl = "My name is <<firstname>> and I am <<age>>";
console.log(
format(tpl, {firstname: 'Bob', age: 33})
)
You could search for string which has the starting pattern and end pattern with look behind and look ahead.
const
string = "My name is <<firstname>> and I am <<age>>",
parts = string.match(/(?<=\<\<).*?(?=\>\>)/g);
console.log(parts);
You could use regex, group, matchAll and get the first group
const string = "My name is <<firstname>>, from <<place>>, and I am <<age>>"
const getVariables = string => {
return [...string.matchAll(/<<(\w+)>>/g)].map(match => match[1])
}
console.log(getVariables(string))
This question already has answers here:
How to get the nth occurrence in a string?
(14 answers)
Closed 2 years ago.
For example, I have a string like following
var string = "test1;test2;test3;test4;test5";
I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.
var substring = "test3;test4;test5";
Now I want to have substring like following
var substring2 = "test4;test5"
How to achieve this in JavaScript
You mean this?
const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items
If the string is very long, you may want to use one of these versions
How to get the nth occurrence in a string?
As a function
const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => {
const arr = string.split(";")
return arr.slice(pos).join(";"); // from item #pos
};
console.log(restOfString(string,2))
console.log(restOfString(string,3))
Try to use a combination of string split and join to achieve this.
var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))
This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 3 years ago.
I want to match all occurrence in string.
Example:
pc+pc2/pc2+pc2*rr+pd
I want to check how many matched of pc2 value and regular expression is before and after special character exists.
var str = "pc+pc2/pc2+pc2*rr+pd";
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));
But I got only +pc2/ and +pc2* and /pc2+ not get in this.
Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.
How do I solve this problem?
You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is p
let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
op.push(array1[0])
if(str1[regex1.lastIndex] === 'p'){
regex1.lastIndex--;
}
}
console.log(op)
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I want to split a string by a variable number of successive characters
splitBy4('XXXXXXXX') => ['XXXX', 'XXXX']
Before injecting the variable it worked all fine :
console.log('XXXXXXXX'.split(/(\w{4})/).filter(Boolean));
// outputs : ['XXXX', 'XXXX']
console.log('XXXXXXXX'.split(new RegExp(/(\w{4})/)).filter(Boolean));
// outputs : ['XXXX', 'XXXX']
But when I try to use the RegExp class + string representation (to inject my parameter), it fails :
console.log('XXXXXXXX'.split(new RegExp('(\w{4})')).filter(Boolean));
// outputs ['XXXXXXXX']
const nb = 4;
console.log('XXXXXXXX'.split(new RegExp('(\w{'+ nb +'})')).filter(Boolean));
// outputs ['XXXXXXXX']
What am I missing and how can I inject my parameter ?
Thanks
const nb = "4";
var myRegex = new RegExp('(\\w{' + nb + '})', 'g');
var myArray = myRegex.exec('XXXXXXXX');
console.log(myArray.toString());
This question already has answers here:
What does the "Nothing to repeat" error mean when using a regex in javascript?
(7 answers)
Closed 4 years ago.
I'm trying to clear a string of any invalid characters to be set as a directory.
Tried a number of methods and this one eventually worked[custom encoding] but now it doesn't, it says "nothing to repeat" in the console. What does that mean? using Chrome.
Here's the code(using random string):
var someTitle = "wa?";
var cleanTitle = cleanTitle(someTitle);
function cleanTitle(title){
var obstructions = ['\\','/',':','*','?','"','<','>','|'];
var solutions = [92,47,58,42,63,34,60,62,124];
var encodedTitle = title;
for (var obstruction = 0; obstruction < obstructions.length; obstruction++){
var char = obstructions[obstruction];
if (encodedTitle.includes(char)){
var enCode = "__i!__"+solutions[obstruction]+"__!i__";
var rEx = new RegExp(char,"g");
encodedTitle = encodedTitle.replace(rEx,enCode);
}
}
console.log("CLEAN: "+title);
console.log("ENCODED: "+encodedTitle);
return encodedTitle;
}
Heres the error:
Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to
repeat
It points to this line -> var rEx = new RegExp(char,"g");
You need to escape some characters when using them as literals in a regular expression. Among those are most of the characters you have in your array.
Given your function replaces the obstruction characters with their ASCII code (and some wrapping __i!__), I would suggest to make your function a bit more concise, by performing the replacement with one regular expression, and a callback passed to .replace():
function cleanTitle(title){
return title.replace(/[\\/:*?"<>|]/g, function (ch) {
return "__i!__"+ch.charCodeAt(0)+"__!i__";
});
}
var someTitle = "wh*r* is |his?";
var result = cleanTitle(someTitle);
console.log(result);
...and if you are in an ES6 compatible environment:
var cleanTitle = t=>t.replace(/[\\/:*?"<>|]/g, c=>"__i!__"+c.charCodeAt(0)+"__!i__");
var someTitle = "wh*r* is |his?";
var result = cleanTitle(someTitle);
console.log(result);
The ? is a regex modifier. When you want to look for it (and build a regex with it), you need to escape it.
That beeing said, a harmless unuseful escaping doesn't hurt (or makes your other search params useable, as there are many modifiers or reserved chars in it) your other search params. So go with
var char = '\\' + obstructions[obstruction];
to replace them all with a (for the regex) string representation
/?/ is not a valid regex. For it to be a regex, you need /\?/.
Regex here would be awkward, as most of the characters need escaping. Instead, consider using a literal string replacement until it is no longer found:
while( encodedTitle.indexOf(char) > -1) {
encodedTitle = encodedTitle.replace(char,enCode);
}