Javascript string concatenate in the wrong order - javascript

I'm trying to generate a character from these three arrays. My code is as follows, but I can't figure out why the string doesn't concatenate as I've written. Some of it is missing, and the ending . even comes at the start at some times. Occasionally it works, but a lot of the times the output fails.
//Arrays
var character = ["man", "woman"];
var feature = ["one leg", "a drinking problem"];
var purpose = ["stay home", "leave home"];
function createSentence(){
var char = getRandomItem(character);
var feat = getRandomItem(feature);
var purp = getRandomItem(purpose);
var sentence = "A " + char + " with " + feat + ", that wants to " + purp + ".";
return sentence;
}
// Gets a random item from an input array
function getRandomItem(array){
var index = Math.floor(Math.random()*array.length);
return array[index];
}
Here's what I get in my console. . at the start and missing the "character"-part.
.with a drinking problem, that wants to leave home
EDIT: Sorry for not including this, as I guess this is very relevant here as well. I assumed the arrays were fine, but I might be missing something. When I print out the arrays after parsing them they look exactly like what I posted above.
// How i set up my arrays
var character = parseTextFile("character.txt");
var feature = parseTextFile("feature.txt");
var purpose = parseTextFile("purpose .txt");
// Parsing a file
function parseTextFile(filename){
var array = fs.readFileSync(filename).toString().split("\n");
return array;
}
/* --- character.txt ---*/
man
woman
Thank you.

// How i set up my arrays
var character = parseTextFile("character.txt");
var feature = parseTextFile("feature.txt");
var purpose = parseTextFile("purpose .txt");
// Parsing a file
function parseTextFile(filename){
//fs.read requires absolute path
var array = fs.readFileSync(__dirname + '/' + filename, 'utf8') // <-- specify format
.split('\n')
.filter(function(text) { return !!text; }); // <-- return only not-empty string
return array;
}

Related

Javascript cut string by begin and end and store in array

I need a algorithm which is doing something like this:
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day"
Output --> ["Hello ", "$$user$$", " your real name is ", "$$realname$$", ". Have a good day"]
Hence, split the part by a selected character and put them together in a string array. Can someone help me out?
I'm looking for a solution with JavaScript/jQuery
It seems you want to split by pattern $$...$$; You could use /(\$\$.*?\$\$)/; To keep the pattern in the result, you can make it a capture group, and also make it lazy (?) so that it will split with the shortest length pattern matched:
example.split(/(\$\$.*?\$\$)/)
#[ 'Hello ',
# '$$user$$',
# ' your real name is ',
# '$$realname$$',
# '. Have a good day' ]
Yes, this is possible with JavaScript itself... Slightly tricky, but yes.
var strings = [], tokens = [];
var str = "Hello $$user$$ your real name is $$realname$$. Have a good day".replace(/\$\$(.*?)\$\$/g, "\$\$TOKEN$1\$\$").split("$");
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf("TOKEN") === 0) {
// This is a token.
tokens.push(str[i].replace("TOKEN", ""));
} else {
strings.push(str[i]);
}
}
str = str.map(function (v) {
if (v.indexOf("TOKEN") === 0)
return "$$" + v.replace("TOKEN", "") + "$$";
return v;
});
console.log(str);
console.log(strings);
console.log(tokens);
The above code will split everything into tokens. And on top of it, it also separates the strings and tokens out. The above one gives as per your requirement:
[
"Hello ",
"$$user$$",
" your real name is ",
"$$realname$$",
". Have a good day"
]
Kindly note, there's nothing like {value, value}, there's only [value, value].
String.split()
The split() method splits a String object into an array of strings by separating the string into substrings.
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day";
var exSplit = example.split("$$");
var userIdx = exSplit.indexOf("user");
var nameIdx = exSplit.indexOf("realname");
document.querySelector(".user").innerHTML = exSplit[userIdx];
document.querySelector(".name").innerHTML = exSplit[nameIdx];
<div class="user"></div>
<div class="name"></div>
Though, if I may suggest, variables can handle this type of operation without all of the hassle.

Javascript Regex get elements from text

I'm quite new to the javascript world an have no idea about regex; I hope you can help me with that one:
I need a function that gives me the elements of a text-block that a user can input through an <input/ on a website, so i can output them to another <input/.
Generalized input:
txt1/txt2_txt3#txt4_txt5#txt6
Real input-example ("personalcode"):
user/855042,5_512125#2431072,25_729106#coursname optionaladdition
What I got so far is the html stuff and this (-yep thats not much):
var base= document.getElementsByName("personalcode")[0].value;
What I would need to get out is:
var one = txt1; //always letters
var two = txt2; //always a decimal number
var three = txt3; //always a decimal number
var four = txt4; //always a decimal number
var five = txt5; //always a decimal number
var six = txt6; //can be letters and decimal numbers
There will never be special characters such as !"§$%&/()=?+*# inside a text element. ö, ü, ä is possible.
Example:
var one = user;
var two = 855042,5;
var three = 512125;
var four = 2431072,25;
var five = 729106;
var six = coursname optionaladdition;
In the end I want to output it like this:
document.getElementsByName("output-user")[0].value= one;
.
.
.
I hope you understand what I mean.
var str = "user/855042,5_512125#2431072,25_729106#coursname optionaladdition";
var arr = str.split(/\/([\d,]+)_([\d,]+)#([\d,]+)_([\d,]+)#/);
# => ["user", "855042,5", "512125", "2431072,25", "729106", "coursname optionaladdition"]
I hope i understand you right what you want to achieve.
I made a small fiddle for you how to get your Data.
https://jsfiddle.net/zasg4zgx/6/
Here is the Code:
<form>
Login :
<input id="logthis" type="text" name="fnName" value="user/855042,5_512125#2431072,25_729106#coursname Löcher in Socken flicken">
<input type="button" value="Login" onClick="javascript:SeperateLoginString(logthis.value)">
</form>
With the id i can transfer the Value of the login field to the function.
function SeperateLoginString(logData) {
var seperateString = [];
var temp = new String(logData);
temp = temp.replace(/#/g, ' ').replace(/_/g, ' ').replace(/#/g, ' ').replace(/\//g, ' ');
seperateString = temp.split(" ");
var user = seperateString[0];
var value1 = seperateString[1];
var value2 = seperateString[2];
var value3 = seperateString[3];
var value4 = seperateString[4];
var value5 = seperateString[5];
With this loop you can add the "optionaladdition" to your value.
I managed it so it can have more than one value
for (var i = 6; i < seperateString.length; i++) {
value5 += " " + seperateString[i];
}
alert(value5);
}
Regards,Miriam
Since you are asking for six different variables, I suggest you use six different input tags. This would be easier for the user and especially for you as a developer. Parsing strings like this is asking for trouble.
However, you could get the values from the string using regex. For example, if you want your first variable (letters only), you could do something like this:
var 1 = text.match(/([A-z])+\//g).slice(0, - 1);
It basically matches a group of characters that starts with letters and ends with a forward slash. The slice method removes the last character from the string (the forward slash).
The second var could be selected like this:
var 2 = text.match(/([0-9])+\#/g).slice(0, - 1);
Still, I recommend you to just use multiple inputs. It's way cleaner and less prone to errors. Good luck!

How to slice long string and output a portion of text

I am capturing the user`s session data into a variable and come out as the following:
"192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1"
I am trying to figure out how to capture the data after FSAPPS\ and before the = so in this case I only want to output BBF4U5C. This would be the login name of the user and may vary in lenght.
Looking for any help at this point.
Try this:
var s = "192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1"
var res = s.split("FSAPPS")[1].split("=")[0];
Here is a hackish way based on finding the start and end indexes in the string. I'm not sure what parts are reliable and what parts aren't but this will work for your specific use case.
var str = "192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1";
var start = str.indexOf("FSAPPS") + 6;
var end = str.indexOf("=1^2");
alert(str.substring(start, end));//alerts BBF4U5C
http://jsfiddle.net/7ssyub7a/
Find index of identifier (index of first letter),
find index od "=" (start looking after identifier)
with this information + known length of identifier you can easily extract sub string containing your login, (bonus points for not destroying your original string)
var txt =
"192605238.|1=Identifiant=FSAPPS\BBF4U5C=1^2=Caisse=GTD95600=1^3=Editeur=False=1^5=Pvp=PVPTSP=1";
var start = txt.indexOf("FSAPPS");
var end = txt.indexOf("=", start);
var login = txt.substring(start + 6, end);

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

Removing a string in javascript

I have a URL say
dummy URL
http://www.google.com/?v=as12&&src=test&img=test
Now I want to remove the &src=test& part alone.I know we can use indexof but somehow I could not get the idea of getting the next ampersand(&) and removing that part alone.
Any help.The new URL should look like
http://www.google.com/?v=as12&img=test
What about using this?:
http://jsfiddle.net/RMaNd/8/
var mystring = "http://www.google.com/?v=as12&&src=test&img=test";
mystring = mystring.replace(/&src=.+&/, ""); // Didn't realize it isn't necessary to escape "&"
alert(mystring);
This assumes that "any" character will come after the "=" and before the next "&", but you can always change the . to a character set if you know what it could be - using [ ]
This also assumes that there will be at least 1 character after the "=" but before the "&" - because of the +. But you can change that to * if you think the string could be "src=&img=test"
UPDATE:
Using split might be the correct choice for this problem, but only if the position of src=whatever is still after "&&" but unknown...for example, if it were "&&img=test&src=test". So as long as the "&&" is always there to separate the static part from the part you want to update, you can use something like this:
http://jsfiddle.net/Y7LdG/
var mystring1 = "http://www.google.com/?v=as12&&src=test&img=test";
var mystring2 = "http://www.google.com/?v=as12&&img=test&src=test";
var final1 = removeSrcPair(mystring1);
alert(final1);
var final2 = removeSrcPair(mystring2);
alert(final2);
function replaceSrc(str) {
return str.replace(/src=.*/g, "");
}
function removeSrcPair(orig) {
var the_split = orig.split("&&");
var split_second = the_split[1].split("&");
for (var i = split_second.length-1; i >= 0; i--) {
split_second[i] = replaceSrc(split_second[i]);
if (split_second[i] === "") {
split_second.splice(i, 1);
}
}
var joined = split_second.join("&");
return the_split[0] + "&" + joined;
}
This still assumes a few things - the main split is "&&"...the key is "src", then comes "=", then 0 or more characters...and of course, the key/value pairs are separated by "&". If your problem isn't this broad, then my first answer seems fine. If "src=test" won't always come first after "&&", you'd need to use a more "complex" Regex or this split method.
Something like:
url = "http://www.google.com/?v=as12&&src=test&img=test"
firstPart = url.split('&&')[0];
lastPart = url.split('&&')[1];
lastPart = lastPart.split('&')[1];
newUrl = firstPart+'&'+lastPart;
document.write(newUrl);
Details: Use the split method.
Solution Edited: I changed the below to test that the last query string exists
var url = "http://www.google.com/?v=as12&&src=test&img=test";
var newUrl;
var splitString = url.split('&');
if (splitString.length > 3)
{
newURL = splitString[0] + "&" + splitString[3];
}
else
{
newURL = splitString[0];
}

Categories