I use this regex
str = "asd34rgr888gfd98";
var p = str.match(/\d{2}/);
alert(p[0]);
butI not understood how can use variable as quantificator, that is how write this:
var number = 2;
var p = str.match(/\d{number}/);
P.S. I see this page JavaScript regex pattern concatenate with variable
but not understood how use example from these posts, in my case.
You need to build your regex as a string and pass it to the RegExp constructor:
var regexString = '\\d{' + number + '}';
var regex = new RegExp(regexString);
var p = str.match(regex);
Notice that when building a regex via a string, you need to add some extra escape characters to escape the string as well as the regex.
var number = "2"
var p = new RegExp("\\d{" + number + "}");
This should work:
var str = "asd34rgr888gfd98";
number = 3;
p = str.match(new RegExp('\\d{' + number + '}'));
alert(p[0]);
Related
I have this string
/results?radius=4000&newFilter=true
and I need to replace radius=4000 with radius=n where n is a variable.
How can I use String.replace() method with regex to match that part?
You can use /radius=\d+/ to match "radius=" followed by any number of digits. With this we can use the replace() method to replace it with the desired value:
var str = "/results?radius=4000&newFilter=true";
var replacement = 123;
var newStr = str.replace(/radius=\d+/, "radius=" + replacement);
console.log(newStr);
If you want to get all parameters you can try this :
function getParams(uri) {
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(uri)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
var str='/results?radius=4000&newFilter=true';
str = str.substring(str.indexOf("?"));
params = getParams(str);
console.log(params);
console.log('radius => ', params['radius']);
This answer is from this post: How to get the value from the GET parameters?
It should be as easy as
var str='/results?radius=4000&newFilter=true';
var n = 1234;
str = str.replace(/(radius=)(\d+)/, "$1" + n);
var url = "/results?radius=4000&newFilter=true";
// or window.location.href for current url
var captured = /radius=([^&]+)/.exec(url)[1]; // your 4000
var newValue = 5000;
url = url.replace(captured, newValue);
by this way you can use it to get all your requested parameters too
and it is not decimal binded
ES6 with regex using positive lookbehind
const string = '/results?radius=4000&newFilter=true',
n = '1234',
changeRadius = (radius) => string.replace(/(?<=radius=)\d+/, n);
console.log(changeRadius(n));
/* Output console formatting */
.as-console-wrapper { top: 0; }
changeRadius is function that takes one parameter (radius) and performs replacement.
About the regex: \d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.
Other regex
Body of changeRadius() function can be replaced with string.replace(/radius=\d+/, 'radius=' + n). It probably has better performance, but original regex is more direct translation of the problem.
You can use capturing without remembering the match to capture only the numerical value after 'radius='.
var url = "/results?radius=4000&newFilter=true";
var radius = 123;
var newUrl = url.replace(/(?:radius=){1}(\d+)/, radius);
console.log(newUrl); // logs '/results?radius=4000&newFilter=true'0
'
I have a string:
var myStr = 'This is a test';
I would like to make it comma delimited via JavaScript, like so:
var myNewStr = 'This, is, a, test';
What is the best way to accomplish this via JavaScript?
I know I can trim the commas like so:
var myStr = myNewStr.split(',');
And that would give me this:
myStr = 'This is a test';
But I am wanting to do the opposite of course, by adding commas.
You could just replace with regex - it is shorter and no need to split.
var myNewStr = myStr.replace(/ /g,', ');
In case you could also face the string with leading / trailing spaces, just trim it beforehand.
var myNewStr = myStr.trim().replace(/ /g,', ');
Try this - var myNewStr = myStr.split(' ').join(', ')
You could use a regular expression with a positive lookahead and replace then with a comma.
console.log('This is a test'.replace(/(?= .)/g, ','));
console.log('This is a test '.replace(/(?= .)/g, ','));
Use String.replace:
var myStr = 'This is a test';
var myNewStr=myStr.replace(/ /g,', ');
You could use the replace function to replace the spaces with commas:
var myStr = myNewStr.replace(' ', ',');
You could also use:
var myStr = myNewStr.split(' ');
Here is a way to do it without using the standard methods.
var myStr = "THIS IS A TEST";
before.innerHTML = myStr;
var parts = [];
var buffer = '';
for(var i = 0; i < myStr.length; i++) {
if(myStr[i] == ' ') {
parts.push(buffer);
buffer = '';
continue;
} else {
buffer += myStr[i];
}
}
parts.push(buffer)
var myNewStr = parts.join(', ');
after.innerHTML = myNewStr;
<div><b>Before</b></div>
<div id="before"></div>
<div><b>After</b></div>
<div id="after"></div>
The solution using String.trim and String.replace functions:
var myStr = ' This is a test ',
myNewStr = myStr.trim().replace(/([^\s]+\b)(?!$)/g, "$&,");
// $& - Inserts the matched substring.
console.log(myNewStr); // "This, is, a, test"
I'm using a regular expression to find all occurrences of a certain string in another string, while ignoring any whitespaces and different cases.
Below is my current code:
var str = word.substring(0,1)+"\\s*";
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
str = str + word.substring(word.length - 1,word.length);
var regEx = new RegExp(str, "gi");
An example would be if var word = "foobar":
var word = "foobar";
var str = word.substring(0,1)+"\\s*"; // declares the string as "f\\s*"
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*"; // will add every character together with \\s* to 'str' like this: "f\\s*o\\s*o\\s*b\\s*a\\s*"
str = str + word.substring(word.length - 1,word.length); // will add the last character without \\s* like this: "f\\s*o\\s*o\\s*b\\s*a\\s*r"
var regEx = new RegExp(str, "gi"); // outputs /f\s*o\s*o\s*b\s*a\s*r/gi
This is working but it does not feel like the best way to solve it. I would be grateful if anyone had a prettier solution to this.
You can use split and join to simplify this:
var word = "foobar";
var regex = new RegExp(word.split('').join('\\s*'), 'gi');
//=> /f\s*o\s*o\s*b\s*a\s*r/gi
I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));
I have the following string:
[27564][85938][457438][273][48232]
I want to replace all the [ with ''. I tried the following but it didn't work:
var str = '[27564][85938][457438][273][48232]'
var nChar = '[';
var re = new RegExp(nChar, 'g')
var visList = str.replace(re,'');
what am I doing wrong here?
Many thanks in advance.
You need to escape the [ otherwise it is interpreted as the start of a character class:
var nChar = '\\[';
If nChar is a variable (and I assume it is otherwise there would be little point in using RegExp instead of /.../g) then you may find this question useful:
Is there a RegExp.escape function in Javascript?
var string = "[27564][85938][457438][273][48232]";
alert(string.replace(/\[/g, '')); //outputs 27564]85938]457438]273]48232]
I escaped the [ character and used a global flag to replace all instances of the character.
I met this problem today.
The requirement is replace all "c++" in user input string. Because "+" has meaning in Reg expression, string.replace fails.
So I wrote a multi-replace function for js string. Hope this can help.
String.prototype.mreplace = function (o, n) {
var off = 0;
var start = 0;
var ret = "";
while(true){
off = this.indexOf(o, start);
if (off < 0)
{
ret += this.substring(start, this.length);
break;
}
ret += this.substring(start, off) + n;
start = off + o.length;
}
return ret;
}
Example:
"ababc".mreplace("a", "a--"); // returns "a--ba--bc"