Way to replace substring that in regular expression with another - javascript

I want to know way to replace substring in url with new string.
https://pbs.twimg.com/media/DW7hPt9VAAAdKE7?format=jpg&name=small
after "&name=" they are many kind of size like
900x900,medium,360x360,small
let href = document.location.href;
if(!href.includes('&name=orig')){
if(href.includes(/900x900|medium|360x360|small/){ //if href have some size in regular expression
// I try to make it search for substring in regular expression
document.location.href = href.replace(/900x900|medium|360x360|small/,'orig');
}
else{ //if url don't have '&name=' like above
var adding = '&name=orig';
document.location.href = link+adding;
}
}
It not working
I don't want to write code to check all case like
if(href.includes('900x900')
if(href.includes('medium')
if(href.includes('360x360')
if(href.includes('small')
they are way to find match at once?

change if(href.includes(/900x900|medium|360x360|small/){ to
if(href.search(/900x900|medium|360x360|small/) !== -1){
as includes accepts the string not the regex.

Related

Get substring after a word and before an filename extension

I have a URL in the following format:
https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg
How to extract hokhqmcmmkveqhxtr0nb from this?
So extract contents between dealetePosts and .jpg
String position, followed by substring would work but is there an easier way?
This is what I have so far and works but is this the best way?
const publicID = dealPic.substring(
dealPic.indexOf("dealetePosts/") + 13,
dealPic.lastIndexOf(".jpg")
);
You can use something like a split and pop method to slash "/" & "." characters. Thats if you are always expecting the same type of url.
let url = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg";
let key = url.split("/").pop().split(".")[0];
console.log(key);
I use the substring function and a regex to remove any extension (jpg, png, etc) and it'works even if dealetePosts changed to anyother name
const test = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg"
function substr(str = ""){
const lastIndexSlash = str.lastIndexOf("/") + 1
return str.substring(lastIndexSlash, str.length).replace(/\.[^/.]+$/, "");
}
console.log(substr(test))
Another option that could be considered easier to read and understand is using regular expressions to match the text you want to extract. The following code will match the text between "dealetePosts/" and ".jpg" and return it as the first captured group:
const publicID = dealPic.match(/dealetePosts\/(.*)\.jpg/)[1];

Is there a more succinct way to get the last number in my url?

So I currently pass two variables into the url for use on another page. I get the last variable (ie #12345) with location.hash. Then from the other part of the url (john%20jacob%202) all I need is the '2'. I've got it working but feel there must be a cleaner and succinct way to handle this. The (john%20jacob%202) will change all the time to have different string lengths.
url: http://localhost/index.html?john%20jacob%202?#12345
<script>
var hashUrl = location.hash.replace("?","");
// function here to use this data
var fullUrl = window.location.href;
var urlSplit = fullUrl.split('?');
var justName = urlSplit[1];
var nameSplit = justName.split('%20');
var justNumber = nameSplit[2];
// function here to use this data
</script>
A really quick one-liner could be something like:
let url = 'http://localhost/index.html?john%20jacob%202?#12345';
url.split('?')[1].split('').pop();
// returns '2'
How about something like
decodeURI(window.location.search).replace(/\D/g, '')
Since your window.location.search is URI encoded we start by decoding it. Then replace everything that is not a number with nothing. For your particular URL it will return 2
Edit for clarity:
Your example location http://localhost/index.html?john%20jacob%202?#12345 consists of several parts, but the interesting one here is the part after the ? and before the #.
In Javascript this interesting part, the query string (or search), is available through window.location.search. For your specific location window.location.search will return ?john%20jacob%202?.
The %20 is a URI encoded space. To decode (ie. remove) all the URI encodings I first run the search string through the decodeURI function. Then I replace everything that is not a number in that string with an empty string using a regular expression.
The regular expression /\D/ matches any character that is not a number, and the g is a modifier specifying that I want to match everything (not just stop after the first match), resulting in 2.
If you know you are always after a tag, you could replace everything up until the "#"
url.replace(/^.+#/, '');
Alternatively, this regex will match the last numbers in your URL:
url.match(/(?<=\D)\d+$/);
//(positive look behind for any non-digit) one more digits until the end of the string

Get a substring from a string for a regular expression in JavaScript

I have a string of the following form:
data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data
It can be in different languages, but in any case I need to get a string which is between the characters ' '
That is, in the example above, I need to get the following string:
view-7631b26ea80b1b601c313b15cc4e2ab03faedf30
Can I do this using the method string.replace(regexp, str) ?
I've highlighted the desired line using the following regular expression:
/'\b(.*)\b'/gm
Now, using the method string.replace I need to delete everything except that...
Got any suggestions?
Use match method.
var data = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
data = data.match(/'\b(.*)\b'/gm)
You have good solid anchor text in either side, so:
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
Live Example:
var str = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
document.body.innerHTML =
"<pre>Got: [" + substr + "]</pre>";
But again, as I said in a comment, using a simple regular expression to extract information from HTML is usually doomed to fail. For instance, you probably don't want to match this:
<p>The string is data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'</p>
...and yet, a simple regex solution will do exactly that. To properly handle HTML, you must use a proper HTML parser.
You can also try this one:
/\'([^\']+)\'/gm

javascript regular expression replacement doesnt work?

why this regular expression replacement doesnt work?
var url = 'http://myweb.com/page/1/id/2';
newUrl = url.replace('/page\/[0-9]+/', 'page/2'); //it must become http://myweb.com/page/2/id/2
You need to do two things:
change str.replace to url.replace
remove the ' around the regex
var url = 'http://myweb.com/page/1/id/2';
newUrl = url.replace(/page\/[0-9]+/, 'page/2');
Example: http://jsfiddle.net/fhqXn/
Use url rather than str, if you want to replace something in the String stored in the url variable.
You have a naming misspell.
Rename your url var to str or change the str.replace to url.replace:
newUrl = url.replace('/page\/[0-9]+/', 'page/2');

Regex to find id in url

I have the following URL:
http://example.com/product/1/something/another-thing
Although it can also be:
http://test.example.com/product/1/something/another-thing
or
http://completelydifferentdomain.tdl/product/1/something/another-thing
And I want to get the number 1 (id) from the URL using Javascript.
The only thing that would always be the same is /product. But I have some other pages where there is also /product in the url just not at the start of the path.
What would the regex look like?
Use window.location.pathname to
retrieve the current path (excluding
TLD).
Use the JavaScript string
match method.
Use the regex /^\/product\/(\d+)/ to find a path which starts with /product/, then one or more digits (add i right at the end to support case insensitivity).
Come up with something like this:
var res = window.location.pathname.match(/^\/product\/(\d+)/);
if (res.length == 2) {
// use res[1] to get the id.
}
/\/product\/(\d+)/ and obtain $1.
Just, as an alternative, to do this without Regex (though i admit regex is awfully nice here)
var url = "http://test.example.com//mypage/1/test/test//test";
var newurl = url.replace("http://","").split("/");
for(i=0;i<newurl.length;i++) {
if(newurl[i] == "") {
newurl.splice(i,1); //this for loop takes care of situatiosn where there may be a // or /// instead of a /
}
}
alert(newurl[2]); //returns 1
I would like to suggest another option.
.match(/\/(\d+)+[\/]?/g)
This would return all matches of id's present.
Example:
var url = 'http://localhost:4000/#/trees/8/detail/3';
// with slashes
var ids = url.match(/\/(\d+)+[\/]?/g);
console.log(ids);
//without slashes
ids = url.match(/\/(\d+)+[\/]?/g).map(id => id.replace(/\//g, ''));
console.log(ids);
This way, your URL doesn't even matter, it justs retrieves all parts that are number only.
To just get the first result you could remove the g modifier:
.match(/\/(\d+)+[\/]?/)
var url = 'http://localhost:4000/#/trees/8';
var id = url.match(/\/(\d+)+[\/]?/);
//With and without slashes
console.log(id);
The id without slashes would be in the second element because this is the first group found in the full match.
Hope this helps people.
Cheers!

Categories