How to use regex to match substring via group repeatedly in JavaScript? - javascript

For example, I have a string:
var s = "ABCDEFGHIJKLMN";
I would like to get an array of substrings whose length is 1 to 5.
The result I expect is:
["ABCDE", "FGHIJ", "KLMN"]
I tried to get the result via regexp.
Here is my code:
var s = "ABCDEFGHIJKLMN";
var result = s.match(/(.{1,5})+/)
But I can only get the last match of the group instead of all of them:
result[1];
"KLMN"

Use split with a capturing group, and remove the empty strings:
var s = "ABCDEFGHIJKLMN";
var result = s.split(/(.{1,5})/).filter(e => e);
console.log(result);

Add a "g" to the end of the pattern:
var s = "ABCDEFGHIJKLMN";
var result = s.match(/.{1,5}/g)
console.log(result)

Related

Javascript split by numbers using regex

I'm trying to come up with a regex that will do following.
I have a string
var input_string = "E100T10P200E3000T3S10";
var output=input_string.split(**Trying to find this**);
this should give an array with all the letters in order with repetitions
output = ["E","T","P","E","T","S"]
See below. \d+ means one or more digits; filter (x => x) removes empty strings that can appear in the beginning or the end of the array if the input string begins or ends with digits.
var input_string = "E100T10P200E3000T3S10";
var output = input_string.split (/\d+/).filter (x => x);
console.log (output);
We can try just matching for capital letters here:
var input_string = "E100T10P200E3000T3S10";
var output = input_string.match(/[A-Z]/g);
console.log(output);
Another approach is spread the string to array and use isNaN as filter callback
var input_string = "E100T10P200E3000T3S10";
var output = [...input_string].filter(isNaN);
console.log(output);
You can use regex replace method. First replace all the digits with empty string and then split the resultant string.
const input_string = 'E100T10P200E3000T3S10';
const ret = input_string.replace(/\d/g, '').split('');
console.log(ret);

How to split string with multiple semi colons javascript

I have a string like below
var exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
I want to split above string with semi colon, so want the array like
var result = [ "Name:Sivakumar ; Tadisetti", "Country:India" ]
But as the name contains another semi colon, I am getting array like
var result = [ "Name:Sivakumar ", "Tadisetti", "Country:India" ]
Here Sivakumar ; Tadisetti value of the key Name
I just wrote the code like exampleString.split(';')... other than this not able to get an idea to proceed further to get my desired output. Any suggestions?
Logic to split: I want to split the string as array with key:value pairs
Since .split accepts regular expressions as well, you can use a one that matches semicolons that are only followed by alphanumeric characters that end in : (in effect if they are followed by another key)
/;(?=\w+:)/
var exampleString = "Name:Sivakumar ; Tadisetti;Country:India";
var result = exampleString.split(/;(?=\w+:)/);
console.log(result)
here is an approach which we first split the input on ; and then concat the element without : with the previous one; since it shouldn't being spited.
let exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
let reverseSplited = exampleString.split(";").reverse();
let prevoiusString;
let regex = /[^:]+:.*/;
let result = reverseSplited.map( str => {
if(regex.test(str)) {
if(prevoiusString){
let returnValue = str + ";" + prevoiusString;
prevoiusString = null;
return returnValue
}
return str
}
prevoiusString = str;
}).filter(e=>e);
console.log(result);

Javascript regex capture giving unexpected results

I am trying to capture all data before the first _. What I have so far is
const regex = /(.*)(?=_)/g;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
The output is an array Array ["Mike_Jones","" ]
What I was expecting was Mike
Use /^[^_]*/
^ looks from the beginning of the string
[^_] negates the _
* gives any number of characters
const regex = /^[^_]*/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
var s = "Mike_Jones_Jr";
console.log(s.split('_')[0]);
Create a capture group ((something between parentheses)) that starts at the beginning of the line (^) and is lazy (.*?), then grab the second item in the matching array.
const regex = /(^.*?)_/s
console.log('Mike_Jones_Jr'.match(regex)[1] || '')
console.log(`Mike
_Jones_Jr`.match(regex)[1] || '')
You can simply use split,
Note:- Second parameter is to limit the number of elements in final outptut
var s = "Mike_Jones_Jr";
console.log( s.split('_', 1) );
If you want to do using regex, you can drop the g flag
const regex = /^[^_]*(?=_)/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
console.log("_ melpomene is awesome".match(regex));

How to find special characters in a string and store in an array in javascript

Example of a string
"/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>"
characters occurs like A, B, C and .... are variables and count is not fixed
How to identifies how many variables are there and stored in an array
Use regex to find all your matches.
Using a while loop you can iterate through multiple matches and push them in an array. Try this.
var String = "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>";
var myRegexp = /\<.\>/gm;
var matches = [];
var match = myRegexp.exec(String);
while (match != null) {
matches.push(match[0])
match = myRegexp.exec(String);
}
console.log(matches)
Please review below code that will help to resolve your issue. It may find any non word characters and create a non-word array.
let str = "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>";
let arrStr = str.split("");
var strRegExp = /\W/g;
let arrNonWord = [];
arrStr.forEach(function(str){
var result = str.match(strRegExp);
if(result)
arrNonWord.push(result[0]);
});
console.log(arrNonWord);

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];

Categories

Resources