I need to replace a dynamic value of a string:
My dynamic value is resulOffset=25
I tried like this:
var str = 'http://example.com?resultLimit=25&resulOffset=25';
var resultOffset = 50;
var newOffset = str.replace(/(resultOffset=)([0-9]+)/, '$1' + resultOffset);
console.log(newOffset);
but doesn't work. How can I solve it?
here: var str = 'http://example.com?resultLimit=25&resulOffset=25';
you have resulOffset instead of resultOffset.
try this one,
var str = 'http://example.com?resultLimit=25&resulOffset={0}';
var resultOffset = 50;
var newOffset = str.replace('{0}',resultOffset);
console.log(newOffset);
Related
I'm trying to replace the values for "min" and "max" price within the following URL string:
var url_full = "http://foo.com/?q=&min=0&max=789"
var url_clean = url_full.replace('&min='+ /\d+/,'');
var url_clean = url_full.replace('&max='+ /\d+/,'');
Struggling to replace the prices.
Replacing min and max values with ''
var url_full = "http://foo.com/?q=&min=0&max=789&hellomin=350"
var url_clean = url_full.replace(/&min=\d+/,'&min=').replace(/&max=\d+/,'&max=')
console.log(url_clean);
> var url = new URL(window.location.href);
> url.searchParams.set('min','100'); window.location.href = url.href;
var url_full = "http://foo.com/?q=&min=0&max=789"
var url_clean = url_full.replace('&min='+ /\d+/,'');
var url_clean = url_full.replace('&max='+ /\d+/,'');
console.log(url_clean);
var regex = /\d+/g;
var string = "http://foo.com/?q=&min=0&max=789";
var matches = string.match(regex); // creates array from matches
for(var s=0;s<matches.length;s++){
console.log(matches[s]);
}
document.write(matches);
Use regex and match for finding digits.
Consider the following string "/path1/path2/file.png".
Is it possible to extract "/path1/path2 through an regex? If so can you provide an example and how it works for it? If not what would be the alternative?
I would do it this way:
var str = '/path1/path2/file.png';
var regex = /(?:\/.*\/)(.*)/;
var filename = regex.exec(str)[1];
console.log(filename);
JSFiddle: https://jsfiddle.net/Ldpoqf0n/1/
this is another way without using regex:
var parts = str.split('/');
console.log(parts[parts.length - 1]);
let str = '"/path1/path2/file.png"';
console.log(str.replace(/\/\w+.\w+"/, ''));
Try this
const src = '/path1/path2/file.png'
const getFirstPart = src => (src.match(/\/.*?\/.*?(?=\/)/) || [])[0]
console.log(getFirstPart(src))
With regexes:
var path = "/path1/path2/file.png";
var patt = new RegExp("\/.*?\/[^\/]*");
var subpath = patt.exec(path)[0];
console.log(subpath)
Without regexes:
function getSubpath(path, subpathLevel) {
var arr = path.split("/");
var subpath = "";
for(var i = 0; i < subpathLevel && i < arr.length; i++)
subpath += "/" + arr[i+1];
return subpath;
}
console.log(getSubpath("/path1/path2/file.png", 2));
In subpathLevel variable you can set the quantity of slashes you want to consider (in the example is 2).
JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf
I want to replace G$0 in the string gantt(G$0,$A4,$B4) with gantt(<>G$0<>,$A4,$B4). So I have the following code:
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var val2 = val.replace(/\$/, "\\$")
var reg = new RegExp(val2, 'g');
var str = str.replace(reg, '<>' + val + '<>');
The result in IE is: =gantt(<>GG$0<>,$A4,$B4) (note the GG). The problem seems to be IE10 specific.
Why is this happening, is this an IE bug?
The replace should assume a string could contain multiple instances of **G$0**.
There's no need to use RegEx at all. Stick to regular string replacement, and you won't have to escape the val string.
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var result = str.replace(val, '<>' + val + '<>');
If you want to replace multiple instances of val this can be done with .split and .join:
var str = '=gantt(G$0,$A4,$B4,G$0) ';
var val = "G$0";
var result = str.split(val).join('<>' + val + '<>');
var value = "ID=advIcon1&CLASS=advIcon&PAGE=43&TOP=2%&LEFT=15%&WIDTH=20%&HEIGHT=10%&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner&ICON=http://203.80.1.28/FlippingBook/Dev/Frontend/source/adv/tc_bn_314.jpg&ALT=Cannon Adv"
What I would like to achieve is from
&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner
to
&RSC=http://www.canon.com.hk/40th/index.html?source#seriesbanner
which replace all the "=" between &RSC and &ICON
value = value.replace (/&RSC=%[=]+%&ICON/,/&RSC=%[#]+%&ICON/);
The above is the code I tried, not working though, how to fix the problem ? thanks
I would do it like this:
var value = "ID=advIcon1&CLASS=advIcon&PAGE=43&TO...";
var startIndex = value.indexOf("&RSC");
var endIndex = value.indexOf("&ICON");
var head = value.substring(0, startIndex);
var tail = value.substring(endIndex);
var body = value.substring(startIndex, endIndex);
var result = head + body.replace(/=/g, '#') + tail;
I don't see any advantage in trying to do the whole thing with one crazy regex.
That will only make your code harder to read and less efficient.
Better yet, make it a function you can re-use:
// Replaces every occurrence of replaceThis with withThis in input between
// startPattern and endPattern.
function replaceCharactersBetween(input, startPattern, endPattern, replaceThis, withThis) {
var startIndex = input.indexOf("startPattern");
var endIndex = input.indexOf("endPattern");
var head = input.substring(0, startIndex);
var tail = input.substring(endIndex);
var body = input.substring(startIndex, endIndex);
var regex = new RegExp(replaceThis, 'g');
return head + body.replace(regex, withThis) + tail;
}
Try:
value = value.replace(/RSC=([^=]+)=([^=]+)/, 'RSC=$1#$2');
You should look at endoceURIComponent() as well.