I have string like this - "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
In here I have three urls, how can i separate them and push them into an array. the url's can be start with http or https or directly from www or any valid url. I want the output like -
[
"https://gaana.com/song/dil-chahte-ho",
"https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm",
"https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
]
Try this:
var t = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
t = t.split("http").map(x => { return "http"+x }).slice(1)
First split the string on "http", which gives you an array. Then append the http to each element of the string. Unfortunately you end up with the first element in the array being "http" that's why you need to slice to remove it.
You can do that with the following code in Python:
links_str = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
links = ["http"+str(link) for link in links_str.split("http")][1:]
Maybe you can try to do something like this in JavaSript.
var urls = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
urls = urls.split("https://").map(val => { return "https://"+val }).slice(1)
console.log(urls);
try this one it will help to split https value in the string
const string = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
const http = string.split("http://").map(val => { return "http://"+val }).slice(1)
const https = string.split("https://").map(val => { return "https://"+val }).slice(1)
const array = [...http, ...https]
console.log(array)
One more way add to space or other delimiter before http and split string:
const str = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm";
const result = str.replace(/http/g, ' $&').split(' ');
// result ["", "https://gaana.com/song/dil-chahte-ho", "https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm", "https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"]
For some reason I had to convert a String with multiple URLS to an Array. So I used a regex to handle the urls and .match() method for creating an Array.
let urls = '[https://website.com/slug, https://website.com/other-slug]';
function convertUrlStringToArray(urls) {
let expression = /\b(https?:\/\/\S*\b)/g;
let regex = new RegExp(expression);
return urls.match(regex);
}
Output an Array:
[ 'https://website.com/slug', 'https://website.com/other-slug' ]
Related
I have an array of urls that get pulled in with "videoJsonUrl" and i'm trying to get a variable from the urls that come in _id=XXXXXXXX
this is what I have so far, which works if I add the url in it manually:
const VideoUrl = "https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761"
const strs = VideoUrl.split('_id=');
const videoId = strs.at(-1)
console.log("Get Content Video ID",videoId);
I cant for the life of me get it to work "videoJsonUrl" though, I think the problem is that "videoJsonUrl" actually contains 3 urls, like this:
can anyone give me any pointers on how to do it?
You can construct a new URL object from each address, then use its searchParams property to get the parameter value of interest:
const urls = [
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447823',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447915',
];
const results = urls.map(url => {
const id = new URL(url).searchParams.get('oauth2_token_id');
return id;
});
console.log(results); // [ "57447761", "57447823", "57447915" ]
URLSearchParams instances have a built-in entries iterator so this should also be fine:
const urls = [
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447823',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447915',
];
const results = urls.map(url => {
const { oauth2_token_id } = Object.fromEntries(new URL(url).searchParams)
return oauth2_token_id;
});
console.log(results) // [ '57447761', '57447823', '57447915' ]
Since ids are all numeric, use a regular expression with a capturing group.
const rx = /_id=(\d+)/g
const m = rx.exec(url)
const ids=[]
while (m) {
ids.push(m[1])
m = rx.exec(url)
}
Use a Set if you need unique values. Use a Map and another capturing group if you need to capture the prefixed id name.
Or just parse the query string and get the values directly from the query map.
For example:
I have a array
const tags = ['size-1', 'size-2', 'discount-xyz']
In this case to check if I have a substring with discount in it, I have converted the array to a string
const arrayToString = tags.toString();
The output:
const tagsArrayToString = size-1,size-2,discount-wyx;
And I check if with a IF statement like this:
if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }
So far so good. But how can I get the full String like "discount-xyz"?
I wouldn't convert the tags array to a string - you already have the strings nice and separated, and this would only make things harder.
Instead, you could filter the array:
const filteredTags = tags.filter(t => t.includes('discount'));
Or, if you know there's just one such string, you could use find to get it:
const relevantTag = tags.find(t => t.includes('discount'));
Find the index of the discount tag using findIndex method, in turn find the tag itself via the index of the array.
const index = tags.findIndex(t => t.indexOf('discount') !== -1);
const discountTag = tags[index];
How to convert below string to array in Javascript? The reason is that I want to take both value separately.
The string is value from an element, when I print it to console I got:('UYHN7687YTF09IIK762220G6','Second')
var data = elm.value;
console.log(data);
You can achieve this with regex, like this for example :
const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig
// Long way
const array = [];
let match;
while (match = regex.exec(string)){
array.push(match[1]);
};
console.log(array)
// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))
source
let given_string = "('UYHN7687YTF09IIK762220G6','Second')";
// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0, given_string.length - 1); // remove )
let expected_array = given_string.split(',');
console.log(expected_array);
Unfortunately, my web services response is returning me a String like this:
{"valueStr":"Single"|"valueId":"2019"}
{"valueStr":"Married"|"valueId":"2019"}
{"valueStr":"Divorced"|"valueId":"2020"}
{"valueStr":"Widowed"|"valueId":"2020"}
I need to filter out those with the valueId. For example, all the 2019 or all the 2020.
The response isn't JSON so I can't parse it, and it's not delimited correctly. So I'm stuck trying something unelegant like this:
function parseItemByYear(item){
// replace all | with ,
var modifiedObj = item.replace(/\|/g, ',');
// split into array
var newArr = modifiedObj.split('}');
// remove all
var newestArr = newArr.map(function(item){item.replace(/^\{/g,'')});
// JSON.parse the object
// var lovObj = JSON.parse(modifiedFilingStatusObj);
// capture the current tax year
// replace , with |
// rebuild the object
// return the filtered object
return newestArr;
}
But I'm failing where I'm trying to set newestArr. My RegEx is wrong. Is my approach too complicated? Is there an easier way that I'm not seeing? Thanks for any tips.
I think this is simple and will do the trick.
// Assuming it's single or multiline string
let response = `{"valueStr":"Single"|"valueId":"2019"}
{"valueStr":"Married"|"valueId":"2019"}
{"valueStr":"Divorced"|"valueId":"2020"}
{"valueStr":"Widowed"|"valueId":"2020"}`;
function parseItemByYear(response) {
// Replace '|' with ','
response = response.replace(/\|/g, ',');
// Replace '}{' with any whitespace in between to '},{'
response = response.replace(/}\s?{/g, '},{');
// Make it an array
let arr = JSON.parse(`[${response}]`);
// Return an array of valueId attribute of all array elements
return arr.map(item => item.valueId);
}
console.log(parseItemByYear(response));
You should have split it by new line \n and the just use JSON.parse as it resembles JSON enough to be parsed.
const response = `{"valueStr":"Single"|"valueId":"2019"}{"valueStr":"Married"|"valueId":"2019"}{"valueStr":"Divorced"|"valueId":"2020"}{"valueStr":"Widowed"|"valueId":"2020"}`;
function parseItemByYear(response){
// replace all `|` with `,`
response = response.replace(/\|/g, ',');
// replace all `}` with `}**BREAK**`
response = response.replace(/\}/g, '}**BREAK**');
// split into array
const newArr = response.split('**BREAK**');
// Remove last emenet added by regexp
newArr.pop()
try {
return newArr.map(item => JSON.parse(item)/*.valueId*/);
} catch(e) {
return new Error('Coud not be parsed');
}
}
console.log(parseItemByYear(response));
This is a list of data handling to get only valueID.
This code is only here to work without JSON (in case of need) but you should consider use standardised format.
const str = `{"valueStr":"Single"|"valueId":"2019"}
{"valueStr":"Married"|"valueId":"2019"}
{"valueStr":"Divorced"|"valueId":"2020"}
{"valueStr":"Widowed"|"valueId":"2020"}`
const results = str.replace(/[\{\}\"]/g, "").split("\n").map(el => el.split("|").map(kv => kv.split(':')).filter(arr => arr[0] === 'valueId')).map(el => el[0][1])
console.log(results)
It's always better to use valid stanrd like JSON, use this toJSON function to transform your string into a valid JSON object easier to use.
const str = `{"valueStr":"Single"|"valueId":"2019"}
{"valueStr":"Married"|"valueId":"2019"}
{"valueStr":"Divorced"|"valueId":"2020"}
{"valueStr":"Widowed"|"valueId":"2020"}`
const toJSON = (str) => JSON.parse('[' + (str
.replace(/(?:\r\n|\r|\n)/g, '')
.replace(/\|/g, ",")
.replace(/}{/g, "},{")) + ']')
console.log(toJSON(str))
console.log(toJSON(str).map(el => el.valueId))
I have a link that comes in as a string, for example:
let data = [
'/api/customer’,
'/api/customer/123’,
'/api/customer/123/details’
];
I need to extract the numeric ID if there is one. The only way I found is trough _.isNaN():
const myStrArray = type.split('/');
const numericsArray = _.filter(myStrArray, urlPart => !_.isNaN(parseInt(urlPart, 10)));
const id = numericsArray[0]; // undefined/123
Is there a better way to do this?
You can iterate the array with Array.flatMap() (or lodash _.flatMap()), and use String.match() with a RegExp to get a sequence of numbers.
Note: this RegExp assumes that these are the only numbers in the string. You might want to fine tune it, if there's a possibility for other numbers.
let data = [
'/api/customer',
'/api/customer/123',
'/api/customer/123/details'
];
const result = data.flatMap(str => str.match(/\d+/));
console.log(result);
User regex and Array#map and Array#flat like so. You need to use ||[] in case a number was not found.
const data = [
'/api/custome',
'/api/customer/123',
'/api/customer/123/details'
];
const res = data.map(a=>a.match(/\d+/)||[]).flat();
console.log(res);