Javascript regex match number after string - javascript

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
'

Related

Javascript-split() not working when there are repeated chars in a string

Not sure how valid is this approach, but I'm unable to split the string into 2 when there are repeated characters.
var match = 's';
var str = "message";
var res = str.split(match, 2);
For instance i tried to use split() on the string "message", it results into:
me,""
So i did this:
res = str.split(match, 3);
so now it resulted into:
me,,age
but as you can see im still missing the second 's' in the "message" string. what im trying to get is I'm passing a matched character (in above case var match which is dynamically generated) to the split() and splitting into 2. I was hoping to get something this:
res = me,,sage
is that possible using split() or is there a better method to achieve this?
P.S: in fiddle i've given another string eg: (string = "shadow") which works fine.
Fails only when there are repeated letters in the string!
fiddle: https://jsfiddle.net/ukeeq656/
EDIT::::::::::::
Thanks everyone for helping me out on this...and so sorry for last min update on the input, i just realized that var match; could be a word too, as in var match = 'force'; and not just var match ='s'; where the string is "forceProduct", so when my match is more than just a letter, this approach works: str.split(match, 2);, but str.indexOf(match); doesnt obviously... could there be an approach to split: "","Product". My extreme apologies for not mentioning this earlier.any help on this would be appreciated!!
eg fiddle:
https://jsfiddle.net/ukeeq656/3/
I don't think split() is the correct way to do this.
Please see below:
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res =[];
res[0] = str.substring(0, index);
res[1] = " ";
res[2] = str.substring(index + 1);
console.log(res);
I'm not sure what your end goal is but I think this gets you what you want.
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res = str.substring(0, index) + ',' + str.substring(index + 1);
alert(res); // me,sage
You could write a function to do this;
function newSplit(str, match) {
var num = str.indexOf(match);
var res = [];
res.push(str.substring(0, num));
//res.push(str.substring(num + 1, str.length)); // this line has been modified
res.push(str.substring(num + match.length, str.length));
return res;
}
var match = 'force';
var str = 'forceProduct';
console.log(newSplit(str, match));
This is what you want?

How to get substring after last specific character in JavaScript?

I have a string test/category/1. I have to get substring after test/category/. How can I do that?
You can use String.slice with String.lastIndexOf:
var str = 'test/category/1';
str.slice(0, str.lastIndexOf('/') + 1);
// => "test/category/"
str.slice(str.lastIndexOf('/') + 1);
// => 1
The actual code will depend on whether you need the full prefix or the last slash. For the last slash only, see Pedro's answer. For the full prefix (and a variable PREFIX):
var PREFIX = "test/category/";
str.substr(str.lastIndexOf(PREFIX) + PREFIX.length);
You can use below snippet to get that
var str = 'test/category/1/4'
str.substring(str.lastIndexOf('/')+1)
A more complete compact ES6 function to do the work for you:
const lastPartAfterSign = (str, separator='/') => {
let result = str.substring(str.lastIndexOf(separator)+1)
return result != str ? result : false
}
const input = 'test/category/1'
console.log(lastPartAfterSign(input))
//outputs "1"
var str = 'test/category/1';
str.substr(str.length -1);
You can use the indexOf() and slice()
function after(str, substr) {
return str.slice(str.indexOf(substr) + substr.length, str.length);
}
// Test:
document.write(after("test/category/1", "test/category/"))
var str = "test/category/1";
pre=test/category/;
var res = str.substring(pre.length);
You can use str.substring(indexStart(, indexEnd)):
var str = 'test/category/1';
var ln=str.length;
alert(str.substring(ln-1,ln));

JavaScript get character in sting after [ and before ]

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

concat variable in regexp pattern

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

Looking for a regex to parse parameters string for JS

I cannot find out the regex to get param value from the part of query string:
I need to send parameter name to a method and get parameter value as result for string like
"p=1&qp=10".
I came up with the following:
function getParamValue(name) {
var regex_str = "[&]" + name + "=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
// check if result found and return results[1]
}
My regex_str now doesn't work if name = 'p'. if I change regex_str to
var regex_str = name + "=([^&]*)";
it can return value of param 'qp' for param name = 'p'
Can you help me with regex to search the beginning of param name from right after '&' OR from the beginning of a string?
This might work, depending on if you have separated the parameter part.
var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";
Looks like split will work better here:
var paramsMap = {};
var params = string.split("&");
for (var i = 0; i < params.length; ++i) {
var keyValue = params[i].split("=", 2);
paramsMap[keyValue[0]] = keyValue[1];
}
If you desperately want to use a regex, you need to use the g flag and the exec method. Something along the lines of
var regex = /([^=]+)=([^&]+)&?/g;
var paramsMap = {};
while (true) {
var match = regex.exec(input);
if (!match)
break;
paramsMap[match[1]] = match[2];
}
Please note that since the regex object becomes stateful, you either need to reset its lastIndex property before running another extraction loop or use a new RegExp instance.
Change your regex string to the following:
//pass the query string and the name of the parameter's value you want to retrieve
function getParamValue(my_query_string , name)
{
var regex_str = "(?:^|\&)" + name + "\=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
try
{
if(results[1] != '')
{
return results[1];
}
}
catch(err){};
return false;
}

Categories