String.split with regexp bug [duplicate] - javascript

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());

Related

Javascript replace regex using [duplicate]

This question already has answers here:
Removing Numbers from a String using Javascript
(2 answers)
Closed 3 years ago.
I need to change #x ( x a number) to x.
How can I do that, I don't know js regex..
You can try like this.
var n = Number(s.replace(/\D+/, ''))
> var s = "#123";
undefined
>
> var n = s.replace(/\D+/, '')
undefined
>
> n
'123'
>
> n = Number(n)
123
>
> n + 7
130
>
Just use replace like so:
const str = "#1235";
const num = str.replace("#", "");
console.log(num);
You can use inbuilt replace function for this purpose, which can take both, literals and regex pattern as parameter.
var str = "#12345";
str.replace("#", "");
We can also use patterns in the replace parameter, if you have multiple values to be replaced.
var str = "#123#45";
str.replace(/[##]/,"") // prints "123#45" => removes firs occurrence only
str.replace(/[##]/g,"") // prints "12345"
str.replace(/\D/,"") // prints "123#45" => removes any non-digit, first occurrence
str.replace(/\D/g,"") // prints "12345" => removes any non-digit, all occurrence
g stands for global search
[##] stands for either # or #, you can add anything here
\D stands for anything other than digits

Regex replace with captured [duplicate]

This question already has answers here:
Using $0 to refer to entire match in Javascript's String.replace
(2 answers)
Closed 5 years ago.
I want replace all non alphanumeric character in the string by it self surrender for "[" and "]".
I tried this:
var text = "ab!#1b*. ef";
var regex = /\W/g;
var result = text.replace(regex, "[$0]");
console.log(result);
I was expecting to get:
ab[!][#]1b[*][.][ ]ef
But instead i get:
ab[$0][$0]1b[$0][$0][$0]ef
How can I do this using Javascript(node)?
You need to wrap the group in parentheses to assign it to $1, like this:
var text = "ab!#1b*. ef";
var regex = /(\W)/g;
var result = text.replace(regex, "[$1]");
console.log(result);

How can I extract only the integer from a String JavaScript [duplicate]

This question already has answers here:
How to find a number in a string using JavaScript?
(9 answers)
Closed 6 years ago.
I have a string that looks like:
var a = "value is 10 ";
How would I extract just the integer 10 and put it in another variable?
You could use a regex:
var val = +("value is 10".replace(/\D/g, ""));
\D matches everything that's not a digit.
you can use regexp
var a = "value is 10 ";
var num = a.match(/\d+/)[0] // "10"
console.log ( num ) ;
You can use some string matching to get an array of all found digits, then join them together to make the number as a string and just parse that string.
parseInt(a.match(/\d/g).join(''))
However, if you have a string like 'Your 2 value is 10' it will return 210.
You do it using regex like that
const pattern = /\d+/g;
const result = yourString.match(pattern);

How can I parse a string and split it into two parts at a special character with javascript? [duplicate]

This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 8 years ago.
How can I take a string and split it at a special character into two new variables (and remove the special chars) with javascript?
For example take:
var X = Peggy Sue - Teacher
and turn it into:
varnew1 = Peggy Sue
varnew2 = Teacher
I guess it should also include a condition... if the string has a "-" then do this.
.split is probably what you want. Here is a very simple example
JSFiddle Link
var string = 'Peggy Sue - Teacher'
var new1 = string.split('-')[0].trim();
var new2 = string.split('-')[1].trim();
console.log(new1); // "Peggy Sue"
console.log(new2); // "Teacher"
And if you want to place a simple condition on it looking for - you can do so with the following
var string = 'Peggy Sue - Teacher'
var new1 = string.indexOf('-') !== -1 ? string.split('-')[0].trim() : string
var new2 = string.indexOf('-') !== -1 ? string.split('-')[1].trim() : string
Second Fiddle
var result = str.split("-");
will give you an array with 2 members,
result[0] = Peggy Sue
result[1] = Teacher

Return only a part of the match [duplicate]

This question already has an answer here:
Get part of the string using regexp [closed]
(1 answer)
Closed 9 years ago.
Here's an example http://jsbin.com/USONirAn/1
var string = "some text username#Jake# some text username#John# some text some text username#Johny# userphoto#1.jpg#";
var type = "username";
var regexp = new RegExp(type + "#(.*?)#");
var matches = string.match(regexp);
Current regexp returns into matches an array with 3 items - [username#Jake#, username#John#, username#Johny#].
How do I make it return only a strings that I used to search for - (.*?)? In this example is should be an array [Jake, John, Johny]. Is it possible to get this only by changing a regexp function?
Update:
I've also tried to use exec function, but it returns both [username#Jake#, Jake] http://jsbin.com/USONirAn/6
Search-and-don't-replace
var matches = []
string.replace(regexp, function () {
matches.push(arguments[1]);
});
http://jsbin.com/USONirAn/4

Categories

Resources