trim string after keyword or a specific character in angular - javascript

I have this url
/application-form?targetDate=2018-03-21
I want to get the string after the equal sign
How to do that?

use split and array
var param = "/application-form?targetDate=2018-03-21";
var items = param.split("=");
var arr1 = items[0];
var arr2 = items[1];
var result = arr2;

Using lastIndexOf and substr methods of string.
const url = '/application-form?targetDate=2018-03-21';
const lastEqualSignIndex = url.lastIndexOf('=');
const datePart = url.substr(lastEqualSignIndex + 1);
console.log(datePart); // -> '2018-03-21'
Edited: multiple query parameters support
Using match method of string:
const [, targetDateValue] = '/application-form?targetDate=2018-03-21'.match(/[\?&]targetDate=([^&#]*)/);
console.log(targetDateValue); // -> '2018-03-21'

You can use URLSearchParams for this. It's a parser for query strings.
Here's how it's used:
new URLSearchParams('?targetDate=2018-03-21').get('targetDate')
// or if you want to use your URL as-is:
new URLSearchParams('/application-form?targetDate=2018-03-21'.split('?')[1]).get('targetDate')
Be aware that this is not supported on IE. For cross-browser variations of this, you can have a look at this answer.

Related

How to get parts of a URL string using Javascript?

I have this URL:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
now I want to get 2 string from that URL:
#tab-cultura and folclore
how can I get it using Javascript?
url.split('#')[0];
It seems this split is not the right solution:(
"Split" can be correct way to approach this. Pls see below
var url = "mysite.com/categorias/#tab-cultura/folclore/";
let [val1, val2] = url.split('#')[1].split('/')
console.log(val1, val2)
You need to split your URL by / delimiter instead
var url = "mysite.com/categorias/#tab-cultura/folclore/";
var parts = url.split('/');
console.log(parts[2]);
console.log(parts[3]);
Also you can use regex if you don't know position of # in URL
var url = "mysite.com/categorias/category1/category2/#tab-cultura/folclore/";
var parts = url.match(/(#[^\/]+)\/([^\/]+)/);
console.log(parts[1]);
console.log(parts[2]);
With JavaScript’s String.prototype.split function:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
var fields = input.split('/');
var first = fields[0];
var second = fields[1];
var third = fields[2];
var fourth = fields[3];
You can use split('/') like so:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
let [, ,tabCultura, folclore] = url.split('/');
console.log(tabCultura);
console.log(folclore);
Using Array.split() will probably get you what you need — for now, but URLs are inherently quite complicated and you want to make sure the code will function the same way on different servers with variable query parameters etc. It may be more reliable to use built in browser functionality:
const hash = new URL("http://example.com/categorias/#tab-cultura/folclore/").hash
// => "#tab-cultura/folclore/"
hash.split('/')
// => ['#tab-cultura', 'folclore', '']
hash.split('/').filter(i=>i)
// => ['#tab-cultura', 'folclore']
Note: new URL() is not available in IE, but can be polyfilled.

How to extract query string parameters from URL in JavaScript

I have a URL
https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama
I want to get search_terms (Generator+Repair) and geo_location_terms (Adamsville%2C+Alabama)
How I can do this?
The easiest and most idiomatic way to do this in JavaScript is using the URL class:
const url = new URL('https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama')
console.log(url.searchParams.get('search_terms'));
console.log(url.searchParams.get('geo_location_terms'));
MDN reference here.
You can use the following Javascript code to store the GET parameters into an object:
<script>
var URL = "https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama";
var result = {};
URL.substring(URL.indexOf("?") + 1).split('&').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log(result.search_terms);
//OUTPUT: "Generator+Repair"
console.log(result.geo_location_terms);
//OUTPUT: "Adamsville%2C+Alabama"
</script>
You can use the following regex to get the 2 values:
/search_terms=(.*)&geo_location_terms=(.*)/
This is a very basic regex, that starts by matching 'search_terms=' then creates a Group that matches any number of any char up to the '&' sign, then matches 'geo_location_terms=' and finally creates a Group that matches any number of any char.
Your desired output will be in Group 1 and Group 2.
How to use:
var url = 'https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama';
var regex = /search_terms=(.*)&geo_location_terms=(.*)/;
var match = url.match(regex);
var search_terms = match[1];
var geo_location_terms = match[2];

How to convert regex string to regex expression? [duplicate]

So I have a RegExp regex = /asd/
I am storing it as a as a key in my key-val store system.
So I say str = String(regex) which returns "/asd/".
Now I need to convert that string back to a RegExp.
So I try: RegExp(str) and I see /\/asd\//
this is not what I want. It is not the same as /asd/
Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g
Is there a better way to do this?
If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.
var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");
If you do need to store the modifiers, use a regex to parse the regex:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);
This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.
If performance is a concern, use normal string manipulation using String#lastIndexOf:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));
const regex = /asd/gi;
converting RegExp to String
const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);
then back to RegExp
const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);
Requires ES6+.
You can use the following before storage of your regex literal:
(new RegExp(regex)).source
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source
Example:
regex = /asd/
string = (new RegExp(regex)).source
// string is now "asd"
regex = RegExp(string)
// regex has the original value /asd/
let rx = RegExp.apply(RegExp, str.match(/\/(.*)\/(.*)/).slice(1));
A modified version of #PegasusEpsilon answer
StackOverflow saves the day again, thanks #4castle! I wanted to store some regex rules in a JS file, and some in a DB, combine them into an array of objects like so:
module.exports = {
[SETTINGS.PRODUCTION_ENV]: [
{
"key": /<meta name="generator"[\s\S]*?>/gmi,
"value": "",
"regex": true
},
...
]
}
Then, loop through each environment's objects and apply it to a string of text. This is for a node/lambda project, so I wanted to use ES6. I used #4castle's code, with some destructuring, and I ended up with this:
let content = body;
const regexString = replacement.key.toString();
const regexParts = /\/(.*)\/(.*)/.exec(regexString);
const {1: source, 2: flags} = regexParts;
const regex = new RegExp(source, flags);
content = content.replace(regex, replacement.value);
return content;
Works a treat!

replace a string partially with something else

lets say I have this image address like
https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
how is it possible to replace FILE_NAME.jpg with THUMB_FILE_NAME.jpg
Note: FILE_NAME and THUMB_FILE_NAME are not static and fix.
the FILE_NAME is not fixed and I can't use string.replace method.
eventually I don't know the File_Name
Use replace
.replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME")
or if you want to support multiple formats
.replace(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g, "THUMB_FILE_NAME")
Demo
var output = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b".replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME");
console.log( output );
Explanation
(?<=\/) matches / but doesn't remember the match
[^\/]* matches till you find next /
(?=(.jpg) ensures that match ends with .jpg
To match the FILE_NAME, use
.match(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g)
var pattern = /[\w-]+\.(jpg|png|txt)/
var c = 'https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
'
c.replace(pattern, 'YOUR_FILE_NAME.jpg')
you can add any format in the pipe operator
You can use the String's replace method.
var a = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
a = a.replace('FILE_NAME', 'THUMB_FILE_NAME');
If you know the format, you can use the split and join to replace the FILE_NAME.
let str = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
let str_pieces = str.split('/');
let str_last = str_pieces[str_pieces.length - 1];
let str_last_pieces = str_last.split('?');
str_last_pieces[0] = 'THUMB_' + str_last_pieces[0];
str_last = str_last_pieces.join('?');
str_pieces[str_pieces.length - 1] = str_last;
str = str_pieces.join('/');

How to use a variable in a match method with regular expression pattern

I want to get an array in JavaScript from a string, cutting it in half.
Example:
// From this:
var myStr = 'cocacola';
// To this:
var myArray = ['coca', 'cola'];
I tried the following method:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
// This won't work
var myArray = myStr.match(/.{1,strHalf}/g);
// Only this will work fine
var myArray = myStr.match(/.{1,4}/g);
You can do String.slice() to solve this
var myStr = 'cocacola';
let len = myStr.length;
let result = [myStr.slice(0, len/2), myStr.slice(len/2)]
console.log(result);
You'll need to to use the RegExp() constructor and make a string that it understands:
var regexString = "/.{1," + strHalf + "}/g";
var myRegex = new RegExp( regexString );
var myArray = myStr.match( myRegex );
...but be careful doing this; if strHalf is a string containing special characters like / then your RegExp will have weird behaviour.
You can create a non-hardcoded regexp by using the RegExp constructor:
var myArray = myStr.match(new RegExp('/.{1,'+strHalf+'}/g'));
The constructor has no clue that strHalf should be an integer, so make sure you can control that.
This is known to introduce a lot of security issues, please don't use this in production. Regexes are too often used when they shouldn't. If you ever use a regex, do look into other options
There are much better alternatives, but at least it's possible!
You dont need regex for that.
The easiest way is that:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
var array = [myStr.substr(0, strHalf),myStr.substr(strHalf, myStr.length)];
jsfiddle: https://jsfiddle.net/cudg8qc3/
You can just slice the string and place the first element in the first slot, and the second element in the second slot in the array.
var str_len = myStr.length
var my_array = [myStr.slice(0, str_len/2), myStr.slice(str_len/2, str_len)]

Categories

Resources