convert textareas string value to JavaScript array separated by new lines - javascript

I have a textarea where the user can write up to 1000 characters. I need to get the jQuery('#textarea').val() and create an array where each item is a line of the textarea's value. That means:
This is a nice line inside the textarea.
This is another line.
(let's asume this line is empty - it should be ignored).
Someone left more than 2 new lines above.
Should be converted to a JavaScript array:
var texts = [];
text[0] = 'This is a nice line inside the textarea.';
text[1] = 'This is another line.';
text[2] = 'Someone left more than 2 new lines above.';
That way they can be easily imploded for to querystring (this is the qs format required by the provider):
example.com/process.php?q=["This is a nice line inside the textarea.","This is another line.","Someone left more than 2 new lines above."]
I tried both the phpjs explode() and string.split("\n") approaches but they doesn't take care of the extra new lines (aka line breakes). Any ideas?

String.prototype.split() is sweet.
var lines = $('#mytextarea').val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
Note that String.prototype.split is not supported on all platforms, so jQuery provides $.split() instead. It simply trims whitespace around the ends of a string.
$.trim(" asd \n") // "asd"
Check it out here: http://jsfiddle.net/p9krF/1/

Use split function:
var arrayOfLines = $("#input").val().split("\n");

var split = $('#textarea').val().split('\n');
var lines = [];
for (var i = 0; i < split.length; i++)
if (split[i]) lines.push(split[i]);
return lines;

Try this
var lines = [];
$.each($('textarea').val().split(/\n/), function(i, line){
if(line && line.length){
lines.push(line);
}
});

Related

having an issue w/ .split in a JavaScript function that gets the max # of repeating chars per word in a string

I'm writing a JavaScript function that has to take in a string argument & determine the word or words with the maximum number or repeated (or most frequent) non sequential characters and return that word or words.
The way that I went about solving this problem was to first find the maximum number of times a character was repeated per word and record that number to use later in a function to test against every word in the string (or the array of strings as I later split it); if the word met the conditions, it's pushed into an array that I return.
My maxCount function seemed to work fine on its own but when I try to make it work together with my other function to get the words with max repeated chars returned, it's not working in JS Fiddle - it keeps telling me that "string.split is not a function" - I'll admit that the way I'm using it (string.split(string[i]).length) to analyze words in the string letter by letter is a bit unconventional - I hope there's some way to salvage some of my logic to make this work in the functions that can work together to get the results that I want.
Also, I don't know if I'm using Math.max correctly/in a "legal" way, I hope so. I've tried switching my variable name to "string" thinking that would make a difference but it did not even though my arguments are of the string variety and it's a string that's being represented.
Here's a link to my Fiddle:
https://jsfiddle.net/Tamara6666/rdwxqoh6/
Here's my code:
var maxCount = function (word) {
/// var maxRepeats = 0;
var numArray = [];
var string = word;
for (var i = 0, len = string.length; i < len; i++) {
//split the word('string') into letters at the index of i
numArray.push((string.split(string[i]).length) -1);
}
var max = Math.max(...numArray);
return max;
}
///console.log(maxCount("xxxxxxxxxxxxx"));
var LetterCount = function(string){
var repeatedChars = 0;
var wordArray=[];
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
var eachWord = stringArray[i];
var maxRepeats = maxCount(stringArray);
if (repeatedChars < maxRepeats) {
repeatedChars = maxRepeats;
wordArray = [eachWord];
}else if (repeatedChars == maxRepeats) {
wordArray.push(eachWord);
}
}
return wordArray;
};
console.log(LetterCount("I attribute my success to cats"));
//should return ["attribute", "success"]
*** I've tried to map this first function onto the array formed when I split my string at the spaces but it is just returned me an empty array (I also might not have been using map correctly in this example); I also have tried using valueOf to extract the primitive value out of the array from the first function which also didn't work. I'm not really sure what to do at this point or what angle to take- I feel if I understood more what was going wrong I could more easily go about fixing it. Any help would be much appreciated. Thanks!
You are passing an array to maxCount at line 20, while it expects a string:
var maxRepeats = maxCount(stringArray);
You should use:
var maxRepeats = maxCount(eachWord);
If you are getting split is not a function error then first make sure that your string isn't null by printing it on console. If it isn't null then confirm that its a string not an array or some other thing.

javascript: get the normalized from two slightly different strings

I have two strings of equal number of slashes and the same letter in each position. There is always one letter and a square bracket indicating an index. There will always be a corresponding letter in both strings.
var first = "/a/b[1]/c/d[3]/e[1]/f"
var second = "/a/b[1]/c/d[4]/e/f"
I expect output should be
result = "/a/b[1]/c/d/e/f"
This is what I came up with but maybe there's a better way of doing it as it returns /a/b/c/d/e/f which is not what i wanted. http://jsfiddle.net/3PM9H/
var first = "/a/b[1]/c/d[3]/e[1]/f".split("/");
var second = "/a/b[1]/c/d[4]/e/f".split("/");
for (var i=0; i < first.length; i++){
firstMatch = first[i].match(/\[([0-9]+)\]/g);
secondMatch = second[i].match(/\[([0-9]+)\]/g);
if (firstMatch != secondMatch){
first[i] = first[i].replace(/\[([0-9]+)\]/g,'') //get rid of the square bracket.
}
}
first.join("/");
I just solved this here. It's a node project but the main file is dependency-less hence portable.
Use the dynamic programming algorithm to compute the Levenshtein distance, and use that transform to generate the regex. Subsitutes become wildcards, inserts or deletes become optional characters.
var Levenshtein = require('levenshtein-transformation)';
var lev = new Levenshtein(str1, str2);
console.log(lev.regex());

split string and leave the separators intact

I cannot find a good way to split a string using a separator string but leave the separator as the prefix of each element of the resulting array:
from
var s = 'blah0__blah1__blah2';
I need to get
['blah0', '__blah1', '__blah2']
the closest thing that I could get was
s.split(/(__)/);
which returns
['blah0', '__', 'blah1', '__', 'blah2']
but this I would need to traverse to merge the underscores.
Is there a better way?
EDIT:
here is my best effort so far:
'blah__blah1__blah2'.split(/(__[^_]+)/)
// => ["blah", "__blah1", "", "__blah2", ""]
still, there are empty strings in the output...
How about this:
var s = 'blah0__blah__blah'
var s_split = s.match(/(__)?(.(?!__))+./g)
console.log(s_split)
I'm pretty sure it's much more costly (time and memory wise) than simply reiterating and joining after a regular split.
If you replace __ with your separator it should work fine for most cases.
A two-step process.
var s = 'blah0__blah1__blah2';
var blahs = s.split('__');
var scoreBlahs = blahs.map(preScore);
alert(scoreBlahs);
function preScore(b) {
var x;
var result = x.concat('__',b);
return result;
}
'blah0__blah1__blah2'.match(/^[^_]+|_+[^_]+/g);
["blah0", "__blah1", "__blah2"]
Seems to give you what you want. Though It may vary, if your input isn't exactly as you show it.
Just prepend the seperator after you seperate the string
var value = "a,b,c";
var splitter = value.split(",");
for(var i = 0; i < splitter.length; i++) {
alert("," + splitter[i]);
}
Since you know the separator - just add it again later on:
var s = 'blah0__blah1__blah2';
var sep = '__';
var arr = s.split(sep);
for (var i = 1; i < arr.length; i++) {
arr[i] = sep + arr[i];
}
console.log(arr);
You could insert a secondary separator, and split on that, leaving the original intact.
var s = 'blah0__blah1__blah2';
s = s.replace('_', '_$');
s.split('$');

transfer special charcter to normal charcter

I am try to load city name from the XML file using javascript AJAX and finally success on them.
var region=Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar
This is my output; in this output some charcter are non standard US ASCII and I want to change into normal chars, like:
var region:- Ahmadabad,Surat,Vadodara,Rajkot,Bhavnagar,Jamnagar,Nadiad,Gandhinagar,Junagadh,Surendranagar
How can I do that?
This is a pure javascript solution though it is not optimal and might perform not well:
// create a character map to convert one char to another
var charMap = {
"ā" : "a",
"ū" : "u"
};
var region="Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar";
// split original string into char array
var chars = region.split('');
// init new array for conversion result
var charsConverted = [];
// convert characters one by one
for(var i = 0; i < chars.length; i++){
var char = chars[i];
// this will try to use a matching char from char map
// will use original if no pair found in charMap
charsConverted.push( charMap[char] || char);
}
// join array to string
var result = charsConverted.join('');
alert(region);
alert(result);
Again this is just an idea and might need a lot of tweaking.
Code in action: http://jsfiddle.net/L5Yzf/
HTH

JavaScript split function

i like to split a string depending on "," character using JavaScript
example
var mystring="1=name1,2=name2,3=name3";
need output like this
1=name1
2=name2
3=name3
var list = mystring.split(',');
Now you have an array with ['1=name1', '2=name2', '3=name3']
If you then want to output it all separated by spaces you can do:
var spaces = list.join("\n");
Of course, if that's really the ultimate goal, you could also just replace commas with spaces:
var spaces = mystring.replace(/,/g, "\n");
(Edit: Your original post didn't have your intended output in a code block, so I thought you were after spaces. Fortunately, the same techniques work to get multiple lines.)
Just use string.split() like this:
var mystring="1=name1,2=name2,3=name3";
var arr = mystring.split(','); //array of ["1=name1", "2=name2", "3=name3"]
If you the want string version of result (unclear from your question), call .join() like this:
var newstring = arr.join(' '); //(though replace would do it this example)
Or loop though, etc:
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
You can play with it a bit here

Categories