Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I wrote a small function to split a string stored in variable data,
var data = "Apple|Banana";
var _res = data.split('|');
After printing _res on the console, it is Printing as Apple,Banana.
I am looking for an output where each String is printed on a newline, like,
Apple
Banana
your variable _res is an Array because it was created after splitting data. Hence it is getting printed as it is.
If you want a newline print, you need to manually do it. See below Code as an example.
Use case when you want to iterate over your input:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|');
_res.forEach(function(element) {
console.log(element);
});
Use case when you just want to test in console and alert:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|').join('\n');
alert(_res);
console.log(_res);
It sounds like you want the output as a string, in which case you shouldn't use split (which returns an array), but .replace - replace all |s with newlines:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
console.log(res);
Or, with alert:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
alert(res);
You should check Escape notation. You can encode special character which will have special meaning in string.
\n is used to create line breaks in string.You can split() string by , and join() by \n.
let str = 'Apple,Banana'
let newStr = str.split(',').join('\n')
console.log(newStr);
let str = 'Apple,Banana'
document.querySelector('div').innerHTML = str.split(',').join('<br>')
<div><div>
If my understanding to your problem is correct, you want to split the string using "|" and "," characters. In that case you can use pass regex value in your split method parameter.
var _res = d.data.split(/[,|]+/);
You can use this site to generate your regex https://www.regextester.com/
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Not sure how to address this with JavsScript to convert it into a json object to pull the below content, strip the first set of quotes so it becomes a valid JSON.
"{""title"": ""Glasses"",""desc"": ""Wood Custom Build""}"
Any ideas would be appreciated.
Thanks
Before anything, here's a straightforward solution. Each string method is easily google-able if not clear.
const string = `"{""title"": ""Glasses"",""desc"": ""Wood Custom Build""}"`
console.log(string)
// remove first and last
const spliced = string.substring(1, string.length-1)
console.log(spliced)
// replace double double quotes "" with single double quotes "
const replaced = spliced.replace(/""/gi, `"`)
console.log(replaced)
// parse as JSON
const json = JSON.parse(replaced)
console.log(json)
But to go into a bit more details, it depends! Based on the source of this string and what you need out of it, it might be useful to know that JSON keys can indeed have double-quotes " in their names. But the proper way to write it would be:
{ "\"yo\"": 42 }
If you DO need to keep the extra quotes (maybe because they are identifying strings that you have no hand over), then parsing this faulty JSON is more complicated because an opening quote "\" becomes different from a closing one \"".
const string = `"{""title"": ""Glasses"",""desc"": ""Wood Custom Build""}"`
// remove first and last
const spliced = string.substring(1, string.length-1)
console.log(spliced)
// find pairs of double-quotes followed by (some optional space and) : or , or }
const closingQuote = /""(?=\s*[:,}])/g
const replaced_1 = spliced.replace(closingQuote, `\\""`)
console.log(replaced_1)
// find pairs of double-quotes that we haven't replaced yet
const notClosingQuote = /(?<!\\)""/g
const replaced_2 = replaced_1.replace(notClosingQuote, `"\\"`)
console.log(replaced_2)
const json = JSON.parse(replaced_2)
console.log(json)
This method uses regex's positive lookahead and negative lookbehind. IIRC they are somewhat new-ish features in the JS implementation of regex syntax.
This question already has answers here:
Convert JSON string to Javascript array [duplicate]
(4 answers)
Closed 5 years ago.
I have an array of geodata stored as a string, and need to turn into into a array of numbers.
var input = "[34.1103897,-118.0398531]"
var output = [34.1103897,-118.0398531]
Not sure the best way to do this. Any tips/ suggestions appreciated!
The easiest way to convert an array of that format is to use JSON.parse.
Simply:
var input = "[34.1103897,-118.0398531]";
var output = JSON.parse(input);
Assuming the data is always formatted with no whitespace, you could simply remove the first and last characters, and split on ',':
var input = '[34.1303897,-118.0398591]';
var output = input.slice(1, -1).split(',').map(parseFloat);
Alternatively, that syntax is technically valid JSON syntax, so you could just:
var input = '[34.1303897,-118.0398591]';
var output = JSON.parse(input);
However, this could be dangerous depending on where the data comes from.
JSON.parse is the obvious choice, but there is also manual parsing with a regular expression (the following assumes you might also want to match a leading '+'):
var input = "[34.1103897,-118.0398531]"
var output = (input.match(/[+-]?[\d\.]+/g) || []).map(Number);
console.log(output)
You might consider validating the input or the resulting output regardless of the method chosen to convert it to an array.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I used the replace() function to remove the _pc and keep the 1, but it's not working...
function testing()
{
var code = "a1_pc"; //The initial stuff
alert(code); //Printing -> a1_pc
var number = code.split("a"); //Remove the "a"
alert(number); //Printing again -> ,1_pc
number = number.slice(1); //Remove the ","
alert(number); //Printing again -> 1_pc
number = number.replace("_pc", "");
alert(number); //Returns nothing...
}
Your above solution should work perfectly and does so in the example below.
The problem must lay somewhere else within your code.
var text = '1_pc';
text = text.replace("_pc", "");
console.log(text);
if you are certain it is the replace() function causing the problems, you can use either of these 2 alternatives.
If you know that the last 3 characters are always _pc, you could use substring to find all the other characters instead.
var text = '1_pc';
text = text.substring(0, text.length - 3);
console.log(text);
Or very similiar to the solution above, you could use slice which is essentially a much cleaner version of the substring solution.
var text = '1_pc';
text = text.slice(0, -3);
console.log(text);
You can use split() javascript function and get first occurrence of string.
split("string which you want to",limit as 1 for first occurrence only)
var res = text.split("_",1);
it will return 1
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How are you guys doing?
I'd like to ask today if you could help me with a tricky question that I was unable to solve on my own.
I [have] strings that [are] like this.
I was looking for a way to get "have" and "are" and form an array with them using JavaScript. Please notice that this is an example. Sometimes I have several substrings between braces, sometimes I don't have braces at all on my strings.
My attempts focused mostly on using .split method and regex to accomplish it, but the closest I got to success was being able to extract the first value only.
Would any of you be so kind and lend me an aid on that?
I tried using the following.
.split(/[[]]/);
You can use the exec() method in a loop, pushing the match result of the captured group to the results array. If the string has no square brackets, you will get an empty matches array [] returned.
var str = 'I [have] strings that [are] like this.'
var re = /\[([^\]]*)]/g,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
}
console.log(matches) //=> [ 'have', 'are' ]
Note: This will only work correctly if the brackets are balanced, will not perform on nested brackets.
var str = "I [have] strings that [are] like this";
var res = str.split(" ");
The result of res will be an array with the values:
I
[have]
strings
that
[are]
like
this
If you want to get only values between braces, you can use the following regex expression:
var str = "I [have] strings that [are] like this";
var result = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((result = pattern.exec(str)) != null)
{
result.push(match[1]);
}
This is JSFiddle example for you.
Simple as this:
'I [have] strings that [are] like this.'.match(/\[([^\]]*)]/g)
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.