How can I get words from a string, textarea javascript - javascript

I've been working on JavaScript and HTML, I have a text area where the user sets a CSV like this:
17845 hello bye 789
Now I have 17845,hello,bye,789 and I need to extract the values between the commas. I've tried with index Of, but what if the user sets 2 lines instead of 1, how can I get these words? I have thought of separate them getting the "\n".

Javascript function split() will do the trick

var str = '17845,hello,bye,789';
var words = str.split(',');
console.log(words);

Use javascript split() Function

Split function gives u the array.
var sentence ="hello, 123, tedsfd, demo";
var strArr = sentence.split(',');
$.each(strArr,function(key,value){
console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

If I understand it correctly, you are facing issues if the user sets comma separated value in multiple lines instead of one... For that use trim() function to remove all tabs and newline and then use split() function.

Use String.split.It converts strings into arrays, given you provide the delimiter, to separate the string.
var userInput = '17845, hello, bye, 789';
data = userInput.split(',');
console.log(data);
//data[0] = '17845'
//data[1] = 'hello'
//data[2] = 'bye'
//...

Related

javascript split string function not working

I am trying to split a string:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = device_data.split('*');
But it's not working. it's just displaying this string
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = str.split('*');
console.dir(res)
,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555
Instead of creating an array with two elements.
IMHO, you want something like this:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
splitStrArr = str.split('*').filter(str => str != "")
console.log(splitStrArr)
console.log(splitStrArr[0])
console.log(splitStrArr[1])
You are getting a string with a period in the beginning because whatever you are doing leads to the result of String#split being converted to a string. String#split returns an array. An array converted to a string is of the form of element0,element1,element2 ... elements separated by commas.
The result of String#split in your case is ["",...] with 3 elements since your string begins with the character '*' you are searching, so String#split will create an empty string as the first element of the returned array. So the result is exactly as expected, and String#split is working as intended.
get rid of the first character of the string,
mystring.substr(1).split('*')
get rid of the empty strings
mystring.split('*').filter(s=>s!='')
to obtain the desired result.
You can use:
var res = str.split("#");
You can check in Javascript console in browser itself.
As a suggestion/ idea, you can always use the browser console, for example, Chrome browser, to execute simple scripts like these.
This way, you can save time, as it is easier to check your data structures, their internal data.
If you try
var res = str.split('*');
you obtain three elements:
res[0] is '' (empty string)
res[1] is 'HQ,61...'
res[2] is 'HQ,...'

Why is JavaScript's split() method not splitting on ":"?

So to start off, a bit of context. I am pulling data from the following url: "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all" using a GET method. The data returned is a series of Pokemon names and image names in the following format.
Name1:name1.png
Name2:name2.png
...
The list is 151 items long. When I call the typeOf() method "String" is returned, so I am fairly certain it is a String I am dealing with here. What I would like to do is split the String on the delimiters of "\n" and ":".
What I would like:
Name1,name1.png,Name2,name2.png...
After some experimentation with Regex, I found that the Regex to do this was "\n|:". Using this I wrote the following line to split the String apart. I tested this Regex on https://regex101.com and it seems to work properly there.
var splitData = data.split("\n|:");
("data" is the String I receive from the url.)
But instead of splitting the String and placing the substrings into an array it doesn't do anything. (At least as far as I can see.) As such my next idea was to try replacing the characters that were giving me trouble with another character and then splitting on that new character.
data = data.replace("\n", " ");
data = data.replace("/:/g", " ");
var splitData = data.split(" ");
The first line that replaces new line characters does work, but the second line to replace the ":" does not seem to do anything. So I end up with an array that is filled with Strings that look like this.
Name1:name1.png
I can split these strings by calling their index and then splitting the substring stored within, which only confuses me more.
data = data.replace("\n", " ");
var splitData = data.split(" ");
alert(splitData[0].split(":")[1]);
The above code returns "name1.png".
Am I missing something regarding the split() method? Is my Regex wrong? Is there a better way to achieve what I am attempting to do?
Right now you are splitting on the string literal "\n|:" but to do a regex you want data.split(/[:\n]/)
The MDN page shows two ways to build a Regex:
var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');
The following test script was able to work for me. I decided to use the regex in the split instead of trying to replace tokens in the string. It seemed to do the trick for me.
let testResponse = `Abra:abra.png
Aerodactyl:aerodactyl.png`;
let dataArray = testResponse.split(/\n|:/g);
let commaSeperated = dataArray.join(',');
console.log(commaSeperated);
So you can simply use regex by excluding the quotes all together.
You can look at the documentation here for regular expressions. They give the following examples:
var re = /ab+c/;
var re = new RegExp('ab+c');
See below for your expected output:
var data = `Name1:name1.png
Name2:name2.png`;
var splitData = data.split(/[\n:]/);
console.log(splitData);
//Join them by a comma to get all results
console.log(splitData.join(','));
//For some nice key value pairs, you can reduce the array into an object:
var kvps = data.split("\n").reduce((res, line) => {
var split = line.split(':');
return {
...res,
[split[0]]: split[1]
};
}, {});
console.log(kvps);
I tried and this works good.
str.split(/[:\n]/)
Here is a plunker.
plunker

Javascript get value in attribute

I am using jquery .attr in an input type so when I run this
console.log('name: '+$(this).attr('name'));
output is: name: user_project_category[65][skill][9]
How can I get the 65 and 9?
You can use Regular Expressions to extract text from between the brackets into an array and then you can access the array to get the values you want, you can either extract all text between brackets or just the numbers:
var yourInput = "user_project_category[65][skill][9]";
var allMatches = yourInput.match(/\[(.*?)\]/g);
console.log(allMatches[0]);
console.log(allMatches[2]);
var numberMatches = yourInput.match(/\[([0-9]*?)\]/g);
console.log(numberMatches[0]);
console.log(numberMatches[1]);
var data = "name: user_project_category[65][skill][9]";
console.log(data.split("[")[1].slice(0,-1))//use split to get 65] use slice to remove ]
console.log(data.split("[")[3].slice(0,-1))//use split to get 9] use slice to remove ]
You can use split with slice
Assuming this is not dynamic and format is the same.
for dynamic use regex
Use regex.
var output = 'user_project_category[65][skill][9]';
var numbers = output.match(/\d+/g).map(Number);
alert(numbers);
output: 65,9
Do whatever you want to do with number.
working fiddle
Use regular expression or split function in JavaScript
var output= 'user_project_category[65][skill][9]';
output.split(/(\d+)/)[1];
output.split(/(\d+)/)[3];

remove quotes before an array list using jquery

I have been strugling with a problem, I am using
var srlisthidden = $('#hiddenroutList').val();
srlisthidden returns an array of list but in quotes "['0015','0016']"
$.each(srlisthidden, function(i, value) {
});
But because of the double quotes on the beginning of the array,it is not allowing the list to iterate even, I tried many different options to remove the double quotes like regEx and
jQuery.parseJSON('['+srlisthidden+']'), but none of them worked, Please give me solution.
Try this out:
var x = "['0015','0016']"; // The value that you are grabbing
var sol = eval(x); // This returns the value as an array of strings.
Is this what you are trying to achieve?
You can achieve it like this as well
var to_parse = "['0015','0016']";
var array = parse.replace(/\[|]|'/g, '').split(',');
JSON requires inner quotes around strings be double-quotes escaped with a backslash; the parser doesn't play nicely with single quotes.
Clean up your string with regex:
var str = srlisthidden.replace(/\'/g, "\"")
Output: ["0015","0016"] (as a string)
Then parse as JSON:
JSON.parse(str)
Output: ["0015", "0016"] (as an array)

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources