Extract information from string - JavaScript - javascript

I am currently implementing google places autocomplete and the module I am using in React Native gives me the address as a whole string and not in address components. However, I need to have the postal code and city separate. The example response always look like this:
address: 'Calle Gran Vía, 8, 28013 Madrid, Spain
From this string I would need to have an object that looks like this:
{
city: 'Madrid',
postal_code: 28013,
}
How could I achieve this?

It's not the most "clean" or "smooth" answer, but it's something:
var response = "address: 'Calle Gran Vía, 8, 28013 Madrid, Spain";
var subStr = response.split(",")[2];
var obj = {
city: subStr.split(" ")[2],
postal_code: subStr.split(" ")[1]
};
console.log(obj);

For the city I think the best way is to use an array of cities and search it in the string
var str = "Calle Gran Vía, 8, 28013 Madrid, Spain";
var cities = ["Paris", "Berlin", "Madrid"];
var city = cities.filter(function(item) {
if (str.search(item) != -1)
return item;
})[0] || null;
For the postal code you should use a regex depending on the country (a good list of regex by country)

Probably split the string by ',' with array methods, take the third element of the array and split that by ' ', then you have your data points.

If you can always count on it being in that same format, you can do the following.
var splitAdress = address.split(",");
//This will give you ["Calle Gran Vía", " 8", " 28013 Madrid", " Spain"]
splitAdress = splitAdress[2].split(" ");
//This will give you ["", "28013", "Madrid"]
You'll first split the string into an array based on the comma and then follow it up by splitting on the space. The extra element in the second array is due to the space. This is an example of what #CBroe pointed out in the comments.

list=adress.split(",")[2].split()
list[0] gives you the postal code
list[1] gives you the city name
It depend on if there is always a comma in the "Calle Gran Vía, 8", if not you can use instead list=adress.split(",")[-2].split()

You might want to try this.
var address="Calle Gran Vía, 8, 28013 Madrid, Spain";
var splits = address.split(',')[2].trim().split(' ');
var newAdd = {
city : splits[1],
postal_code : splits[0]
}
console.log(newAdd);

Related

How to replace list of words with <span> tag at multiple indexes in Javascript

I have a response of parent string which I have to modify and replace with the provided start and end indexes.
let parentString = '\r\nManchester United won\r\nManchester City lost\r\nLeeds United tied'
let replaceValues =
{value: 'Manchester United', startIndex: 2, endIndex: 19}
{value: 'Manchester City', startIndex: 25, endIndex: 40}
{value: 'Leeds United', startIndex: 47, endIndex: 59}
Expected Final Result:
I tried below approach but was not successful
replaceAt(input: string, index: number, replacement: string, source: string) {
return (
input.substring(0, index) +
replacement +
input.substring(index + source.length)
);
}
Usage:
replaceValues.forEach((replaceMatch: any) => {
parentString = this.replaceAt(
parentString,
replaceMatch.startIndex,
"<span class='replace-text-{{i}}'>${replaceMatch.value}</span>",
replaceMatch.value
);
please ignore my example names couldn't think anything more
EDIT: My previous answer did not account to duplicate and did not use your indexes, so here it is a more consistent answer:
Convert string to array to ease manipulation
const parentArray = Array.from(parentString)
Now we have an array of characters, i.e [" ", " ", "M", "a", "n", "c", "h", ...]
For each item in replaceValues we use splice on our newly created array. Splice acctepts 3 arguments:
First argument is the start index where we want to splice the array.
Second argument is how many items in the array will be deleted/replaced.
Third argument is with what we want to replace the array portion.
let numberOfCharsReplaced = 0
replaceValues.forEach(item => {
parentArray.splice(item.startIndex - numberOfCharsReplaced, item.endIndex - item.startIndex, `<span>${item.value}</span>`)
numberOfCharsReplaced = numberOfCharsReplaced + item.endIndex - item.startIndex - 1
console.log(parentArray, numberOfCharsReplaced)
})
That numberOfCharsReplaced is necessary because since we splice and replace, we need to take account of the number of chars that has been replaced, what I am saying is that when we replace the 'Manchester United' word that has 16 chars, we pass from 16 items in the array to only 1 big word (i.e "<span>Manchester United</span>") so we can't rely on the startIndex of the next value only, we need to do some calculation. It's easier in the code.
We get back our string by using .join(), telling to the join method with which character we want to join each character.
const replacedParentString = parentArray.join("");
If you still wish to have an array of html string, use the split and shift method indicated in the old answer
Please refer to MDN to read more about the methods used in this answer
splice
join
OLD ANSWER
Use values to replace names with their 'html' equivalent within the parent string
replaceValues.forEach(item => {
parentString = parentString.replace(item.value, `<span>${item.value}</span>`)
})
Now you have a string that is like this:
\r\n<span>Manchester United</span> won\r\n<span>Manchester City</span> lost\r\n<span>Leeds United</span> tied
So now you may want this string as an array of html content
let contentsArray = parentString.split("\r\n")
Now we have this:
[
"",
"<span>Manchester United</span> won",
"<span>Manchester City</span> lost",
"<span>Leeds United</span> tied"
]
Finally if you want to get rid of that initial empty string just shift the array once
contentsArray.shift()
If you don't want to use regex you can try this code :
let parentString = '\r\nManchester United won\r\nManchester City lost\r\nLeeds United tied'
let replaceValues = [
{value: 'Manchester United', startIndex: 2, endIndex: 19},
{value: 'Manchester City', startIndex: 25, endIndex: 40},
{value: 'Leeds United', startIndex: 47, endIndex: 59},
];
replaceValues.sort((a,b) => b.startIndex - a.startIndex);
function replaceAt(input, start, end, value) {
let str = input.split('')
str.splice(start, end - start, value);
return str.join('');
}
for(let replace of replaceValues) {
parentString = replaceAt(parentString,replace.startIndex, replace.endIndex, `<span class='replace-text-{{i}}'>${replace.value}</span>`);
}
console.log(parentString);
// Output :
// <span class='replace-text-{{i}}'>Manchester United</span> won
// <span class='replace-text-{{i}}'>Manchester City</span> lost
// <span class='replace-text-{{i}}'>Leeds United</span> tied
I don't know where does {{i}} comes from, but I think you can easily fill it will the correct value
Maybe regex is slightly faster? Seems like you indend to get rid of line breaks?
const parentString = '\r\nManchester United won\r\nManchester City lost\r\nLeeds United tied'
const repalcedString = parentString.replace(/(\r\n|\n|\r)/gm, "");
console.log(repalcedString)

Extract certain Columns and Rows from a json string

I get a JSON response like this from a server,
{
id : 1,
text : 'Name City Country \nJohn \n Chicago \nIllinois \nAlbert \nHouston \nTexas '
}
if I do console.log(response.text); the output is like this in tabular form
Now I want only want the Name column along with the rows and the output should look like this
Suggest me a workaround for this. Since the value is a string I'm facing a lot of trouble to extract only the required columns
I haven't tested this, but something like this should work:
var jsonData = "{ id : 1, text : 'Name City Country \nJohn \n Chicago \nIllinois \nAlbert \nHouston \nTexas ' }";
var obj1 = jsonData.split('\n');
for(var i= 1; i<obj1.length-2; i=i+3)
{
console.log("Name: " +obj1[i]+", City: "+obj1[i + 1]+", Country: " +obj1[i + 2]);
}
Use trim and split to get the Name City and Country texts.
const obj = { id : 1, text : 'Name City Country \nJohn \n Chicago \nIllinois \nAlbert \nHouston \nTexas ' }
console.log(obj.text.split("\n")[0].trim().split(" "));
You can use any of the javascript csv parser to parse the text to csv and access the particular column.
Ref: javascript-code-to-parse-csv-data

Parsing out Salutation & First Name from Full Name field

I have a string that contains Full Name.
The format of the full name may or may not have the salutation. Also there may or may not be a period after the salutation as well (could display as Mr. or Mr). For example, I could receive:
"Mrs. Ella Anderson"
"Ella Anderson"
"Miss Jennifer Sply"
"Mr. Dan Johnson"
"Damien Hearst"
My goal is to remove the salutation from the Full Name string. Once the salutation is removed, I want to parse out the First Name from the Full Name. I am kinda new to regex, but I do understand how to parse out the First Name. The one part I am just not sure how to do is get rid of the salutation.
var string = "Ella Anderson"
var first = string.replace(/\s.*$/, "").toUpperCase().trim();
This regex should work.
var regex = /(Mr|MR|Ms|Miss|Mrs|Dr|Sir)(\.?)\s/,
fullNames = ["Mrs. Ella Anderson", "Ella Anderson", "Miss Jennifer Sply", "Mr. Dan Johnson", "Damien Hearst"];
var names = fullNames.map(function(name) {
var match = regex.exec(name),
n = "";
(match !== null) ? n = name.replace(match[0], "") : n = name;
return n;
});
console.log(names);
The problem is that the full name is in a string in the first place. If at all possible, you should change that to just use separate fields.
There's no telling what users will enter in a text box. Nor is it reliably possible to determine what part of the remaining name is the first name, and what part is the surname.
If the input data is separated properly, you won't have to figure out what is what, any more.
So, if possible, change the way the name is entered to something like:
<select name="select">
<option>Miss</option>
<option>Mrs</option>
<option>Mr</option>
<option>etc...</option>
</select>
<input placeholder="First name" />
<input placeholder="Surname" />
You can use this regexp: /((Mrs|Mr|Miss)\.? )?([^ ]*) ?([^ ]*)/
Examples:
var regex = /((Mrs|Mr|Miss)\.? )?([^ ]*) ?([^ ]*)/;
regex.exec('Mrs. Ella Anderson') == ["Mrs. Ella Anderson", "Mrs. ", "Mrs", "Ella", "Anderson"];
regex.exec("Ella Anderson") == ["Ella Anderson", undefined, undefined, "Ella", "Anderson"];
regex.exec("Miss Jennifer Sply") == ["Miss Jennifer Sply", "Miss ", "Miss", "Jennifer", "Sply"];
regex.exec("Mr. Dan Johnson") == ["Mr. Dan Johnson", "Mr. ", "Mr", "Dan", "Johnson"];
regex.exec("Damien Hearst") == ["Damien Hearst", undefined, undefined, "Damien", "Hearst"];
regex.exec("Missy Jennifer") == ["Missy Jennifer", undefined, undefined, "Missy", "Jennifer"];
If you want the first name and the last name, you just have to look at the last two values of the array.
Of course, this regexp will not work with something like `Mr. John Smith Junior. If you want something generic, don't use a regexp.
It's a pretty complicated regex:
/^(?:(Miss|M[rs]{1,2})\.?\s+)?(\S+)\s+(\S+)$/
Then if you want middle names or initials it gets a little trickier things like jr. or sr. - It's mostly all doable. There's some question about how to deal with hyphenates.
You can use this regexp:^[ \t]*(?<title>(Shri|Leu|DR|mrs|SMT|Major|Gen){1,10}(\.|,))?\s*(?<LstName>[A-Z][a-z-']{2,20}),? +(?<FstName>[A-Z,a-z]+)*[ \t]*[^\n]*
Tested on the following Test data:
Major. Amator Gary L
Mrs. Grundy Ronald
Dr. Domsky Alan
Shri. Worden Scott Allen
Rodriguez Howard W
NEHME ALLEN
RODRIGUEZ CHARLES G
VERGARA WILLIAM F J
EVELYN J
Leu. GLICK, JACOB L.
SMT. Taylor-garcia Dottielou

Extract numbers and words from address string using jquery

I have an address string which varies from address to address.
var address_string = '6-3-54/A/889, Road no 45, Toli Chowki, Bangalore, Karnataka 700065, India'
How can I separate the following fields from the above address_string using jQuery
6-3-54/A/889
Road no 45
Toli Chowki
Bangalore
Karnataka
700065
India
Why jQuery?
what_you_need = address_string.split(', ')
You can use split function as below.
var arr = address_string.split(',');
Access and print as below:
for(var i=0;i<arr.length;i++)
{
document.write(arr[i]);
}
Please refer this link ( JS Fiddle) will help to solve you problem
You can use below code to get numbers(array) from String :
String.prototype.getNums= function(){
var rx=/[+-]?((\.\d+)|(\d+(\.\d+)?)([eE][+-]?\d+)?)/g,
mapN= this.match(rx) || [];
return mapN.map(Number);
};
var s= 'I want to extract 123 and 456 from this string ';
alert(s.getNums());
You can check Length as below :
alert(s.getNums()[0].toString().length);
// and so on

regex: match between

I have a sample string:
iasfa345.12isnhf Lat: 46.7132N, Long: 116.997W EFONA345.55SDF
I need to extract 116.997 and 46.7132 from it.
I only managed to get:
x.match(/Long: .{7}/g)
x.match(/Lat: .{6}/g)
But it includes Long: or Lat: that I need to substr() later.
The perfect solution would be to match any digit and a single dot between "Lat: " and "N or S" and between "Long: " and "W or E"
You could use the exec[MDN] method:
var str = 'iasfaisnhf Lat: 46.7132N, Long: 116.997W EFONASDF',
latPattern = /Lat: (\d*\.\d+)/,
longPattern = /Long: (\d*\.\d+)/;​​​​​​​​​​​​​​​​​​​​​​​​​​
alert(latPattern.exec(str)[1]);
alert(longPattern.exec(str)[1]);
If you need the direction indicators, which it seems like you would, the patterns would be:
/Lat: (\d*\.\d+)(N|S)/
/Long: (\d*\.\d+)(E|W)/
The direction indicators would be at index 2 of the object returned by exec.
Here's a working example.
For this format you can use this:
var str = "iasfaisnhf Lat: 46.7132N, Long: 116.997W EFONASDF";
var values = str.replace(/[^\d.,]/g, "").split(',');
values[0] == "46.7132"
values[1] == "116.997"
Live DEMO
Lat:\s?(.*?)N
Extract the first group and it will contain the latitude.
Long:\s?(.*?)W
Extract the first group and it will contain the longitude.

Categories

Resources