Return a subset of String [duplicate] - javascript

This question already has answers here:
Last segment of URL with JavaScript
(30 answers)
Closed 3 months ago.
I have this string:
'/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'
I want to return only the id ('e78c7cfa-e469-4edd-8a87-9517a5b9e5da') after the last '/'. The id changes everytime I make an API call. How can I do that using any String functions?

You could use match() here:
var input = "/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da";
var output = input.match(/[^\/]+$/)[0];
console.log(output);
Another regex option would be to do a replacement:
var input = "/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da";
var output = input.replace(/^.*\//, "");
console.log(output);

You can use String.prototype.split which splits a string based on the given separator:
const path = '/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'
const parts = path.split('/')
const id = parts[parts.length - 1] // the last chunk
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

You can create a substring from the position of the last / (+ 1 to omit the it) to the end of the string:
str.slice(str.lastIndexOf('/') + 1)
Note: This assumes that the string will always contain a /. If it's possible that it doesn't you have to handle that case.

Related

How to add anything at a specific position in a string using vanilla javascript [duplicate]

This question already has answers here:
Insert a string at a specific index
(19 answers)
Closed 3 years ago.
For Example need to add a slash / in between USDYEN so it need to output USD/YEN.
One way is to FIND and replace USD for USD/ then it will output USD/YEN
However, how about if USD is not found because it's another currency let's say EUR/YEN?
The trick here is to slice or cut the string at a particular position for example at the third character then add a slash / then add the same string but without the first 3 characters.
var str = 'USDYEN'
// add a / in between currencies
// var newStr = str.slice(3) // removes the first 3 chars
// var newStr = str.slice(0,3) // removes the last 3 chars
var newStr = str.slice(0,3) + ' / ' + str.slice(3) // removes the first 3 and adds the last 3
console.log(newStr)
Here the string is being removed
More info into how to use slice()
https://www.w3schools.com/jsref/jsref_slice_string.asp
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))

convert string regex to regex with tag i [duplicate]

This question already has answers here:
Changing the RegExp flags
(4 answers)
Closed 3 years ago.
ok, I have a problem here, in my database I store regexPath that made from URL.
I used this package path-to-regex
so I store my converted path to regex as String in the database like this:
let path = "/v1/manager/notification/all"
let regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"
and I need test() function for checking some condition.
ofcourse test() function need a regex format for checking value is exists in regex.the only way I found in internet for convert string to regex is :
let RegexPattern = new RegExp(regexPath)
but RegExp function consider my i tag as a part of regex him self and it returns something like this:
/"\/^\\\/v1\\\/manager\\\/notification\\\/all\\\/page\\=([^\\=\\\/]+?)(?:\\\/)?$\/i"/
how should I solve this problem?
You need to extract the inner regex and flags before. Here's an example:
const path = "/v1/manager/notification/all"
const regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"
const separator = regexPath.lastIndexOf('/')
const pattern = regexPath.slice(1, separator)
const flags = regexPath.slice(separator + 1)
const regex = new RegExp(pattern, flags)
console.log('Pattern: ' + pattern)
console.log('Flags: ' + flags)
console.log('Regex: ' + regex)
Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp you need to extract the modifiers yourself and pass them in as the second parameter. You will also need to remove the leading and trailing slashes.
new RegExp(pattern[, flags])

javascript Regular Expressions [duplicate]

This question already has answers here:
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
Closed 6 years ago.
I have the following url
http://www.test.info/?id=50&size=40
How do I get the value of the url parameter with regular expressions in javascript . i need the size value and also need the url without &?
only
http://www.test.info/?id=50
Thanks
Consider using split instead of a regex:
var splitted = 'http://www.test.info/?id=50&size=40'.split('&');
var urlWithoutAmpersand = splitted[0];
// now urlWithoutAmpersand => 'http://www.test.info/?id=50'
var sizeValue = splitted[1].split('=')[1] * 1;
// now sizeValue => 40
Just use this as your regex
size.*?(?=&|$)
here is some code you can use
var re = /size.*?(?=&|$)/g;
var myArray = url.match(re);
console.log(myArray);
you also can do it like this:
var re = new RegExp("size.*?(?=&|$)", "g");
Here is a regex pattern you could use.
^(.+)&size=(\d+)
The first group will be the url up to right before the '&' sign. The second group will be the value of the size parameter. This assumes id always comes before size, and that there are only two parameters: id and size.

Extract specific data from JavaScript .getAttribute() [duplicate]

This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed

How to remove all characters after a certain index from a string [duplicate]

This question already has answers here:
Remove everything after a certain character
(10 answers)
Closed 9 years ago.
I am trying to remove all characters from a string after a specified index. I am sure there must be a simple function to do this, but I'm not sure what it is. I am basically looking for the javascript equivalent of c#'s string.Remove.
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];
or
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);
Use substring
var x = 'get this test';
alert(x.substr(0,8)); //output: get this
You're looking for this.
string.substring(from, to)
from : Required. The index where to start the extraction. First character is at index 0
to : Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string
See here: http://www.w3schools.com/jsref/jsref_substring.asp
I'd recommend using slice as you can use negative positions for the index. It's tidier code in general. For example:
var s = "messagehere";
var message = s.slice(0, -4);

Categories