Splitting string in javascript - 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.

Related

How can I split a string but keep the delimiters in javascript?

I have searched online but it really doesnt make much sense.
I am trying to split a string and keep the delimiters too.
For example, I have this string:
var str = '45612+54721/121*124.2';
And, I would like to split it based on the operations & keep the operations.
So the output must look like this
[45612], [+], [54721], [/], [121], [*], [124.2];
If you use strings’ split with a regex, any captured groups become part of the resulting array.
var str = '45612+54721/121*124.2';
var tokens = str.split(/([+/*])/);
console.log(tokens);

Trimming whitespace without affecting strings

So, I recently found this example on trimming whitespace, but I've found that it also affects strings in code. For instance, say I'm doing a lesson on string comparison, and to demonstrate that "Hello World!" and "Hello World!" are different, I need the code compression to not have any effect on those two strings.
I'm using the whitespace compression so that people with different formatting styles won't be punished for using something that I don't use. For instance, I like to format my functions like this:
function foo(){
return 0;
};
While others may format it like this:
function foo()
{
return 0;
};
So I use whitespace compression around punctuation to make sure it always comes out the same, but I don't want it to affect anything within a string. Is there a way to add exceptions in JavaScript's replace() function?
UPDATE:
check this jsfiddle
var str='dfgdfg fdgfd fd gfd g print("Hello World!"); sadfds dsfgsgdf'
var regex=/(?:(".*"))|(\s+)/g;
var newStr=str.replace(regex, '$1 ');
console.log(newStr);
console.log(str);
In this code it will process everything except the quoted strings
to play with the code more comfortably you can see how the regex is working :
https://regex101.com/r/tG5qH2/1
I made a jsfiddle here: https://jsfiddle.net/cuywha8t/2/
var stringSplitRegExp = /(".+?"|'.+?')/g;
var whitespaceRegExp = /\s+\{/g;
var whitespaceReplacement = "{"
var exampleCode = `var str = "test test test" + 'asdasd "sd"';\n`+
`var test2 = function()\n{\nconsole.log("This is a string with 'single quotes'")\n}\n`+
`console.log('this is a string with "double quotes"')`;
console.log(exampleCode)
var separatedStrings =(exampleCode.split(stringSplitRegExp))
for(var i = 0; i < separatedStrings.length; i++){
if (i%2 === 1){
continue;
}
var oldString = separatedStrings[i];
separatedStrings[i] = oldString.replace(whitespaceRegExp, whitespaceReplacement)
}
console.log(separatedStrings.join(""))
I believe this is what you are looking for. it handles cases where a string contains the double quotes, etc. without modifying. This example just does the formatting of the curly-braces as you mentioned in your post.
Basically, the behavior of split allows the inclusion of the splitter in the array. And since you know the split is always between two non-string elements you can leverage this by looping over and modifying only every even-indexed array element.
If you want to do general whitespace replacement you can of course modify the regexp or do multiple passes, etc.

Replace .split() with .match() using regex in javascript

I'm having difficulties with constructing some regular expressions using Javascript.
What I need:
I have a string like: Woman|{Man|Boy} or {Girl|Woman}|Man or Woman|Man etc.
I need to split this string by '|' separator, but I don't want it to be split inside curly brackets.
Examples of strings and desired results:
// Expample 1
string: 'Woman|{Man|Boy}'
result: [0] = 'Woman', [1] = '{Man|Boy}'
// Example 2
string '{Woman|Girl}|{Man|Boy}'
result: [0] = '{Woman|Girl}', [1] = '{Man|Boy}'
I can't change "|" symbol to another inside the brackets because the given strings are the result of a recursive function. For example, the original string could be
'Nature|Computers|{{Girls|Women}|{Boys|Men}}'
try this:
var reg=/\|(?![^{}]+})/g;
Example results:
var a = 'Woman|{Man|Boy}';
var b = '{Woman|Girl}|{Man|Boy}';
a.split(reg)
["Woman", "{Man|Boy}"]
b.split(reg)
["{Woman|Girl}", "{Man|Boy}"]
for your another question:
"Now I have another, but a bit similar problem. I need to parse all containers from the string. Syntax of the each container is {sometrash}. The problem is that container can contain another containers, but I need to parse only "the most relative" container. mystring.match(/\{+.+?\}+/gi); which I use doesn't work correctly. Could you correct this regex, please? "
you can use this regex:
var reg=/\{[^{}]+\}/g;
Example results:
var a = 'Nature|Computers|{{Girls|Women}|{Boys|Men}}';
a.match(reg)
["{Girls|Women}", "{Boys|Men}"]
You can use
.match(/[^|]+|\{[^}]*\}/g)
to match those. However, if you have a nesting of arbitrary depth then you'll need to use a parser, [javascript] regex won't be capable of doing that.
Test this:
([a-zA-Z0-9]*\|[a-zA-Z0-9]*)|{[a-zA-Z0-9]*\|[a-zA-Z0-9]*}

how to check next existence of a character in string in javascript

Hi All I have a string like this
var data='mobile,car,soap,room';
I am parsing from this string and making this string as comma sperated and pushing it into an array like this
var availableTags=[];
var str='';
for(i=0;i<data.length;i++)
{
if(data[i]==',')
{
availableTags .push(str);
str='';
}
else
{
str +=data[i];
}
}
But I am doing wrong as I cannot get the last value after comma... Now What I want to ask how can I come to know the next existence of , in my string that whether it exists or not. So that I can also include the last value.
I would also appreciate if someone guide me that how can I accomplish that same task some other way.
I want the string to be an array and it should look like this
["mobile","car","soap","room"]
you can use
var availableTags = data.split(",");
it will handle all the things. and will result in an array.
You can use:
data.split(/,/)
See the split documentation.
After loop, you need to check value of str and add it too. It can contain the rest after last comma, or it can be empty in case comma was the last character in data.
But as other pointed, split is probably better way to do it.
As far as fixing your existing function, try adding the following after the for loop:
if (str != "")
availableTags.push(str);
(When the loop ends str holds whatever came after the last comma.)
But like the other answers said, you can just use the array .split() method:
var availableTags = data.split(",");
You could append an extra comma on at the start:
data = data + ","
...

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

Categories

Resources