I am loading data about NBA games from an API using Javascript, and I want to manipulate it but am having trouble. Each game is its own separate object, and is the data is returned like this:
Date: "Nov 7, 2014"
Opponent: "# Charlotte"
Result: "L"
Score: "122-119"
Spread: "+1.5"
Depending on whether the team is home or away, there is either a "#" or a "vs" in front of the name of the opponent for that particular game. I want to get rid of this, so that the "Opponent" key only has "Charlotte" as its value in the above example.
I've tried usinggameLog[i].Opponent = (gameLog[i].Opponent.split(" ").pop
to get rid of any characters before the space, but this ruins the data when there is a team name with a space in it like "New York" or "Los Angeles"
This takes the string, and creates a new substring starting at the index of the first white space. e.g.:
# New York = a new string starting after the #. -> New York
gameLog[i].Opponent = gameLog[i].Opponent.substr(gameLog[i].Opponent.indexOf(' ')+1);
I guess, something along these lines might help.
var home = "# Charlotte";
var opponent = "vs New York";
function parse(team){
// Case when it is a home team
if ( team.indexOf("#") === 0 ){
return team.replace("#","").trim();
// Away team
} else {
return team.replace("vs","").trim();
}
}
console.log( parse(home) );
console.log( parse(opponent) );
gameLog[i].Opponent = (gameLog[i].Opponent.split(" ").slice(1).join(" "));
Split based off space character
Slice off the first item in the array
Join the contents of the array back together with space.
You can use regular expressions to replace unwanted characters while looping over an array of objects.
for (var i = 0; i < arr.length; i++) {
arr[i].Opponent = arr[i].Opponent.replace(/#\s|vs\s/g, '');
}
Here's a jsbin
You need the substr() method:
var str = "# Charlotte";
var res = str.substr(2);
Result: Charlotte
Unless there is also a space after "vs", which is not clear.
Then you could use:
var str = "# Charlotte";
var res = str.substr(str.indexOf(' ')+1);
Related
I am using extendscript to build some invoices from downloaded plaintext emails (.txt)
At points in the file there are lines of text that look like "Order Number: 123456" and then the line ends. I have a script made from parts I found on this site that finds the end of "Order Number:" in order to get a starting position of a substring. I want to use where the return key was hit to go to the next line as the second index number to finish the substring. To do this, I have another piece of script from the helpful people of this site that makes an array out of the indexes of every instance of a character. I will then use whichever array object is a higher number than the first number for the substring.
It's a bit convoluted, but I'm not great with Javascript yet, and if there is an easier way, I don't know it.
What is the character I need to use to emulate a return key in a txt file in javascript for extendscript for indesign?
Thank you.
I have tried things like \n and \r\n and ^p both with and without quotes around them but none of those seem to show up in the array when I try them.
//Load Email as String
var b = new File("~/Desktop/Test/email.txt");
b.open('r');
var str = "";
while (!b.eof)
str += b.readln();
b.close();
var orderNumberLocation = str.search("Order Number: ") + 14;
var orderNumber = str.substring(orderNumberLocation, ARRAY NUMBER GOES HERE)
var loc = orderNumberLocation.lineNumber
function indexes(source, find) {
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
alert(result)
}
indexes(str, NEW PARAGRAPH CHARACTER GOES HERE)
I want all my line breaks to show up as an array of indexes in the variable "result".
Edit: My method of importing stripped all line breaks from the document. Using the code below instead works better. Now \n works.
var file = File("~/Desktop/Test/email.txt", "utf-8");
file.open("r");
var str = file.read();
file.close();
You need to use Regular Expressions. Depending on the fields do you need to search, you'l need to tweek the regular expressions, but I can give you a point. If the fields on the email are separated by new lines, something like that will work:
var str; //your string
var fields = {}
var lookFor = /(Order Number:|Adress:).*?\n/g;
str.replace(lookFor, function(match){
var order = match.split(':');
var field = order[0].replace(/\s/g, '');//remove all spaces
var value = order[1];
fields[field]= value;
})
With (Order Number:|Adress:) you are looking for the fields, you can add more fields separated the by the or character | ,inside the parenthessis. The .*?\n operators matches any character till the first break line appears. The g flag indicates that you want to look for all matches. Then you call str.replace, beacause it allows you to perfom a single task on each match. So, if the separator of the field and the value is a colon ':', then you split the match into an array of two values: ['Order number', 12345], and then, store that matches into an object. That code wil produce:
fields = {
OrderNumber: 12345,
Adresss: "my fake adress 000"
}
Please try \n and \r
Example: indexes(str, "\r");
If i've understood well, wat you need is to str.split():
function indexes(source, find) {
var order;
var result = [];
var orders = source.split('\n'); //returns an array of strings: ["order: 12345", "order:54321", ...]
for (var i = 0, l = orders.length; i < l; i++)
{
order = orders[i];
if (order.match(/find/) != null){
result.push(i)
}
}
return result;
}
I am wanting / needing to split a string by a specific character, for instance a '/' that I can reliably expect, but I need to know what the characters directly in front of that character are up to the space before those characters.
For example:
let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"
So, I can split by the '/' already using
mySplitStr = myStr.split('/');
But now mySplitStr is an array like
mySplitStr[1] = "bob u"
mySplitStr[2] = " used cars nr"
mySplitStr[3] = " no resale value i"
etc
I need, however, to know what the characters are just prior to the '/'.
u
nr
i
etc
so that I know what to do with the information following the '/'.
Any help is greatly appreciated.
You could use this regular expression argument for the split:
let parts = myStr.split(/\s*(\S+)\/\s*/);
Now you will have the special characters at every odd position in the resulting array.
let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service";
let parts = myStr.split(/\s*(\S+)\/\s*/);
console.log(parts);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For a more structured result, you could use these special character combinations as keys of an object:
let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service";
let obj = myStr.split(/\s*(\S+)\/\s*/).reduceRight( (acc, v) => {
if (acc.default === undefined) {
acc.default = v;
} else {
acc[v] = acc.default;
acc.default = undefined;
}
return acc;
}, {});
console.log(obj);
I think, this is what you're looking for:
"bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"
.split('/')
.map(splitPart => {
const wordsInPart = splitPart.split(' ');
return wordsInPart[wordsInPart.length - 1];
});
// Produces: ["u", "nr", "i", "bb", "service"]
Splitting by '/' is not enough. You also need to visit every part of your split result and extract the last "work" from it.
After you split your string, you indeed get an array, where the last set of characters is the one you want to know, and you can grab it with this:
let mySplitStr = myStr.split('/');
for(let i = 0; i < mySplitStr.length; i++) {
let mySplitStrEl = mySplitStr[i].split(" "); // Split current text element
let lastCharsSet = mySplitStrEl[mySplitStrEl.length -1]; // Grab its last set of characters
let myCurrentStr = mySplitStrEl.splice(mySplitStrEl.length -1, 1); // Remove last set of characters from text element
myCurrentStr = mySplitStrEl.join(" "); // Join text element back into a string
switch(lastCharsSet) {
case "u":
// Your code here
case "nr":
// Your code here
case "i":
// Your code here
}
}
Inside the loop, for the first iteration:
// lastCharsSet is "u"
// myCurrentStr is "bob"
I'm facing some problem while trying to send text to some spelling API.
The API return the corrections based on the words index, for example:
sentence:
"hello hoow are youu"
So the API index the words by numbers like that and return the correction based on that index:
0 1 2 3
hello hoow are youu
API Response that tell me which words to correct:
1: how
3: you
On the code I using split command to break the sentence into words array so I will be able to replace the misspelled words by their index.
string.split(" ");
My problem is that the API trim multiple spaces between words into one space, and by doing that the API words index not match my index. (I would like to preserve the spaces on the final output)
Example of the problem, sentence with 4 spaces between words:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
I thought about looping the words array and determine if the element is word or space and then create something new array like that:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
That way I could replace the misspelled words easily and than rebuild the sentence back with join command but the problem but the problem that I cannot use non-numeric indexes (its mixed up the order of the array)
Any idea how I can keep the formatting (spaces) but still correct the words?
Thanks
in that case you have very simple solution:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
Please review this one:
For string manipulation like this, I would highly recommend you to use Regex
Use online regex editor for faster try and error like here https://regex101.com/.
here I use /\w+/g to match every words if you want to ignore 1 or two words we can use /\w{2,}/g or something like that.
var str = "Hello howw are youu?";
var re = /\w+/g
var words = str.match(re);
console.log("Returning valus")
words.forEach(function(word, index) {
console.log(index + " -> " + word);
})
Correction
Just realize that you need to keep spacing as it is, please try this one:
I used your approach to change all to space. create array for its modified version then send to your API (I dunno that part). Then get returned data from API, reconvert it back to its original formating string.
var ori = `asdkhaskd asdkjaskdjaksjd askdjaksdjalsd a ksjdhaksjdhasd asdjkhaskdas`;
function replaceMeArr(str, match, replace) {
var s = str,
reg = match || /\s/g,
rep = replace || ` space `;
return s.replace(reg, rep).split(/\s/g);
}
function replaceMeStr(arr, match, replace) {
var a = arr.join(" "),
reg = match || /\sspace\s/g,
rep = replace || " ";
return a.replace(reg, rep);
}
console.log(`ori1: ${ori}`);
//can use it like this
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);
//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);
Updated
var str = "Hello howw are youu?";
var words = str.split(" ");
// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
if (word) {
return word;
}
});
console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");
var response = {
"1": "how",
"3": "you"
}
//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
requestArray[key] = response[key];
}
//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array
var count = 0;
words.forEach(function(word, index){
if (word) {
words[index] = requestArray[count];
count++;
}
})
console.log(words);
Correct me, if i was wrong.
Hope this helps :)
Try this JSFiddle
, Happy coding :)
//
// ReplaceMisspelledWords
//
// Created by Hilal Baig on 21/11/16.
// Copyright © 2016 Baigapps. All rights reserved.
//
var preservedArray = new Array();
var splitArray = new Array();
/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
this.originalIndex = pIndex;
this.apiIndex = nIndex;
this.title = title;
}
/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
splitArray = str.split(" ");
//console.log(splitArray);
var x = 0;
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 0) {
var word = new preservedObject(i, x, splitArray[i]);
preservedArray.push(word);
x++;
}
}
};
function replaceMisspelled(resp) {
for (var key in resp) {
for (var i = 0; i < preservedArray.length; i++) {
wObj = preservedArray[i];
if (wObj.apiIndex == key) {
wObj.title = resp[key];
splitArray[wObj.originalIndex] = resp[key];
}
}
}
//console.log(preservedArray);
return correctedSentence = splitArray.join(" ");
}
/*Your input string to be corrected*/
str = "Hello howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);
//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution
I have the following strings:
str=["If we go to the park, we will find a big slide!"];
replacer=[["to","a"],["a","un"]];
I then iterate through str and replace each occurrence of "to" with "a" and then each occurrence of "a" with "un" and end up with:
str=["If we go un the park, we will find un big slide!"];
I understand that in this simple case I could reverse the replacer values but that is not an option for me. Is there anyway I could put some kind of disclaimer or flag with the replaced word so that when I iterate through for the next variable it skips the already replaced word?
Thanks!
try
var str=["If we go to the park, we will find a big slide!"];
function replacer(str, oldarr, newArr)
{
oldarr.forEach( function(value,index){
str = str.replace( new RegExp(value, "g"), newArr[index] );
} );
return str;
}
replacer(str[0],["to","a"],["a","un"]);
You can split str by space to array, and then iterate over each word, saving "used" index to temporary array not to overwrite it again, then join this array back to string:
var str = ["If we go to the park, we will find a big slide!"];
var replacer = [["to","a"],["a","un"]];
var ar = str[0].split(' ');
var used = [];//temporary array to hold indexes of changes values
replacer.forEach(function(v,k){
ar.forEach(function(x,i){
if(used.indexOf(i) < 0){
if(x == v[0]){
ar[i] = v[1];
used.push(i);
}
}
});
});
str = [ar.join(' ')];
console.log(str);
Output:
["If we go a the park, we will find un big slide!"]
From server I get data as such:
"07.00 PROGRAM DESCRIPTION"
"07.20 PROGRAM DESCRIPTION 2"
I want to split them into a 2 indexed array such as: ["07.00", "PROGRAM DESCRIPTION 2"]. Regular split( " " ) would not work me as the description part contains severaral " " spaces.
I will be grateful for any suggestion.
Regards
You could use:
var parts = str.split(' '),
time = parts.shift(),
description = parts.join(' ');
or, to get your array:
var parts = str.split(' ');
parts[1] = parts.slice(1).join(' ');
;)
You need somekind of a pattern, which is reliable. If it's always the case that you need to split just between the first whitespace character to you can do:
var blub = "07.00 PROGRAM DESCRIPTION",
pos = blub.indexOf(" "),
arr = [];
arr[0] = blub.slice(0, pos);
arr[1] = blub.slice(pos + 1);
or you might just want to use regular expression. Since I don't pretend to be a genius on that field here is my little suggestion:
var blub = "07.00 PROGRAM DESCRIPTION",
arr = /(\d+\.\d+)\s(.*)/.exec(blub);
var pattern = /([0-9]{2}\.[0-9]{2})\s(.+)/;
var data = "07.00 PROGRAM DESCRIPTION";
var parsed = pattern.exec(data);
console.log(parsed); // (Array) ["07.00 PROGRAM DESCRIPTION", "07.00", "PROGRAM DESCRIPTION"]
this is flexible and easier to adapt in case the format changes (just change the pattern and use that var anywhere else in your code)
The substring method:
var time = row.substring(0,4);
var description = row.substring(5);
Or, with the split method:
row = row.split(" ",1);
The second parameter is the maximum number of splits... so it'll only split at the first space. Edit: this won't work. Use the first method instead.