Removing commas unless inside quotes, not using regexp - javascript

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)

Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.

This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);

Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

Related

How to String include after character in nodejs, JavaScript

I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);

Javascript Replace with Global not working on Caret Symbol

i have following code for replacing
var temp = "^hall^,^restaurant^";
temp.replace(/^/g, '');
console.log(temp);
This does not Replace the ^ symbol from string. How can this not work?
temp = temp.replace(/\^/g, '');
It is replacing once you escape the caret.
https://jsfiddle.net/ym7tt1L8/
And note that just writing temp.replace(/\^/g, ''); doesn't update your actual string. That is the reason you have to write
temp = temp.replace(/\^/g, '');
In RegEx, the caret symbol is a recognized as a special character. It means the beginning of a string.
Additionally, replace returns the new value, it does not perform the operation in place, youneed to create a new variable.
For your case, you have to do one of the following:
var temp = "^hall^,^restaurant^";
var newString = temp.replace(/\^/g, ''); // Escape the caret
Or simply replace the character without using RegEx at all:
var temp = "^hall^,^restaurant^";
while (temp.indexOf('^') >= 0) {
temp = temp.replace('^', '');
}
Alternative version:
var temp = "^hall^,^restaurant^";
var newString = temp.split('^').join('');

Regex doesn't seem to work properly in my code

What I am trying to do is turn, for example "{{John}}" into "John".
First I am parsing from a string:
var parametrar = content.match(/[{{]+[Aa-Åå]+[}}]/g);
Here regex works fine and it parses as it should. I need to parse the "{}" to find stuff in the string.
But then I'm trying to parse out the "{}" from each "parametrar":
for (var i = 0; i < parametrar.length; i++) {
parametrar = parametrar[i].replace(/[{}]/g, "");
}
When I alert "parametrar" all I get is one "a". I have no idea what I'm doing wrong here, seems it should work.
Try to add greedy matching to maque's answer with using question mark(?).
"{{John}}".replace(/\{\{(.*?)\}\}/g,"$1");
It extracts "John" properly from "{{John}} and Martin}}" input. Otherwise it matches to "John}} and Martin".
You can match the name with braces around and then just use the first capturing group (m[1]):
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = '{{John}}';
if ((m = re.exec(str)) !== null) {
paramterar = m[1];
alert(paramterar);
}
If you have a larger string that contains multiple {{NAME}}s, you can use the code I suggested in my comment:
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = 'My name is {{John}} and {{Vasya}}.';
var arr = [];
while ((m = re.exec(str)) !== null) {
paramterar = m[1];
arr.push(m[1]);
}
alert(arr);
alert(str.replace(/([a-zA-ZÅå])\}{2}/g,"$1").replace(/\{{2}(?=[a-zA-ZÅå])/g, ""))
I have also fixed the character class to only accept English letters + Å and å (revert if it is not the case, but note that [Aa-Åå] is not matching any upper case Englihs letters from B to Z, and matches characters like §.) Please check the ANSI table to see what range you need.
Just do it like that:
"{{John}}".replace(/\{\{(.*)\}\}/g,"$1");
So you are searching for string that have double '{' (these needs to be escaped), then there is something (.*) then again '}' and your output is first match of the block.
Try this:
var parametrar = content.replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
This gives you a "purified" string. If you want an array, than you can do this:
var parametrar = content.match(/\{\{[a-åA-Å]+\}\}/g);
for (var i = 0, len = parametrar.length; i < len; i++) {
parametrar = parametrar[i].replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
}

Using regular expression to split a string

I have a string which I need to separate correctly:
self.view.frame.size.height = 44
I need to get only view, frame, size, and height. And I need to do it with a regular expression.
So far I've tried a lot of variants, none of them are even close to what I want to get. And my code now looks like this:
var testString = 'self.view.frame.size.height = 44'
var re = new RegExp('\\.(.*)\\.', "g")
var array = re.exec(testString);
console.log('Array length is ' + array.length)
for (var i = 0; i < array.length; i++) {
console.log('<' + array[i] + ">");
}
And it doesn't work at all:
Array length is 2
<.view.frame.size.>
<view.frame.size>
I'm new at Javascript, so maybe I want the impossible, let me know.
Thanks.
In Javascript, executing a regexp with the g modifier doesn't return all the matches at once. You have to execute it repeatedly on the same input string, and each one returns the next match.
You also need to change the regexp so it only returns one word at a time. .* is greedy, so it returns the longest possible match, so it was returning all the words between the first and last .. [^.]* will match a sequence of non-dot characters, so it will just return one word. You can't include the second . in the regexp, because that will interfere with the repetition -- each repetition starts searching after the end of the previous match, and there's no beginning . after the ending . of the word. Also, there's no . after height, so the last word won't match it.
EDIT: I've changed the regexp to use \w* instead of [^.]*, because it was grabbing the whole height = 44 string instead of just height.
var testString = 'self.view.frame.size.height = 44';
var re = /\.(\w*)/g;
var array = [];
var result;
while (result = re.exec(testString)) {
array.push(result[1]);
}
console.log('Array length is ' + array.length)
for (var i = 0; i < array.length; i++) {
console.log('<' + array[i] + ">");
}
If you're sure that your data will be always in the same format you can use this:
function parse (string) {
return string.split(" = ").shift().split(".").splice(1);
}
In your context, split is a MUCH better option:
var str = "self.view.frame.size.height = 44";
var bits1 = str.split(" ")[0];
var bits2 = bits1.split(".");
bits2.shift(); // get rid of the unwanted self
console.log(bits2);

JS split() function that ignores separator appearing inside quotation marks

Basically, like if you were to say
var string = 'he said "Hello World"';
var splitted = string.split(" ");
the splitted array would be:
'he' 'said' '"Hello World"'
basically treating the quotation mark'd portion as a separate item
So how would I do this in javascript? Would I have to have a for loop that goes over the string checking if the scanner is inside a set of quotation marks? Or is there a simpler way?
You could use regular expressions:
var splitted = string.match(/(".*?")|(\S+)/g);
Basically it searches at first for strings with any characters between quotes (including spaces), and then all the remaining words in the string.
For example
var string = '"This is" not a string "without" "quotes in it"';
string.match(/(".*?")|(\S+)/g);
Returns this to the console:
[""This is"", "not", "a", "string", ""without"", ""quotes in it""]
First of all, I think you mean this:
var string = 'he said "Hello World"';
Now that we've got that out of the way, you were partially correct with your idea of a for loop. Here's how I would do it:
// initialize the variables we'll use here
var string = 'he said "Hello World"', splitted = [], quotedString = "", insideQuotes = false;
string = string.split("");
// loop through string in reverse and remove everything inside of quotes
for(var i = string.length; i >= 0; i--) {
// if this character is a quote, then we're inside a quoted section
if(string[i] == '"') {
insideQuotes = true;
}
// if we're inside quotes, add this character to the current quoted string and
// remove it from the total string
if(insideQuotes) {
if(string[i] == '"' && quotedString.length > 0) {
insideQuotes = false;
}
quotedString += string[i];
string.splice(i, 1);
}
// if we've just exited a quoted section, add the quoted string to the array of
// quoted strings and set it to empty again to search for more quoted sections
if(!insideQuotes && quotedString.length > 0) {
splitted.push(quotedString.split("").reverse().join(""));
quotedString = "";
}
}
// rejoin the string and split the remaining string (everything not in quotes) on spaces
string = string.join("");
var remainingSplit = string.split(" ");
// get rid of excess spaces
for(var i = 0; i<remainingSplit.length; i++) {
if(remainingSplit[i].length == " ") {
remainingSplit.splice(i, 1);
}
}
// finally, log our splitted string with everything inside quotes _not_ split
splitted = remainingSplit.concat(splitted);
console.log(splitted);​
I'm sure there are more efficient ways, but this produces an output exactly like what you specified. Here's a link to a working version of this in jsFiddle.

Categories