split method to return only values split by a comma not quotes in comma [closed] - javascript

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 2 days ago.
Improve this question
I want to split the string below by a default comma which is , and ignore the "," part.
Has anyone come up with a solution for this? Tried a bunch of solutions, but doesn't work.
My string: (testing","a framework), hello world, testing","antother_framework
expected result:
["testing","a framework", "hello world", "testing","antother_framework]

not the nicest way, with regex you could grouped the replace but it works
const str = '(testing","a framework), hello world, testing","antother_framework';
let arr = str.split(',');
console.log(arr);
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll('(', '');
arr[i] = arr[i].replaceAll(')', '');
arr[i] = arr[i].replaceAll('\"', '');
arr[i] = arr[i].trim();
}
console.log(arr);

You could use this function:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);
}
Explanation:
/,(?=(?:[^"]"[^"]")[^"]$)/ -> match the comma outside of the quotes
(?:[^"]"[^"]")* -> match the quotes and the text inside the quotes
[^"]*$ -> match the remaining text after the last quote
If you run the function like this:
console.log(splitByCommas('(testing","a framework), hello world, testing","antother_framework'));
It will give the following output:
[
'(testing","a framework)',
' hello world',
' testing","antother_framework'
]
If you want to also trim the whitespaces, you can use this:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (item) {
return item.trim();
}
);
}
For the same input giving you:
[
'(testing","a framework)',
'hello world',
'testing","antother_framework'
]

Related

how to get first character of second string in javascript? [closed]

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 11 months ago.
Improve this question
how to get first 2 character of string in javascript like this "Hello world " => get this "wo"?
another example
"Osama Mohamed" => M.
you can use string.split(' '), this function will split you string into an array, for example:
let s = "Hello World";
console.log(s.split(" ")) // will log ["Hello", "World"]
then you can get the second word using array[index] when index the index of your desired word in said array.
now using string charAt we can get the first letter of the word.
now to put everything together:
let s = "Hello World"
let s_splited = s.split(" ") // ["Hello", "World"]
let second_word = s_splited[1]
console.log(second_word.charAt(0))
string = "Hello world";
split_string = string.split(" ");
second_word = split_string[1]
first_char = second_word[0]
console.log(first_char)
OR
string = "Hello world";
console.log(string.split(" ")[1][0])

Reverse the given String in Javascript [closed]

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 2 years ago.
Improve this question
I have a situation to manipulate a given string which is separated by comma and reverse the given string.
Input: hello,world,wow
Expected Output: wow,world,hello
First split the string by the comma. Then reverse the array. Then turn it back into a string.
let foo = 'hello,world,wow' // assign the string
foo = foo.split(',') // splits by comma
foo = foo.reverse() // reverses the array
foo = foo.join() // converts array back into a comma separated string
var initialString = "hello,world,wow"
var finalString = initialString.split(",").reverse().join(",");
console.log(finalString) // "wow,world,hello"
Here is the solution to reverse the given string.
let str = "hello,world,wow";
let temp = str.split(",");
let output = "";
// Index will starting from last element
let index = (temp.length - 1);
for(let k=0; k<temp.length; k++){
if(k == (temp.length - 1)){
// Last Element so no need of comma
output += temp[index];
}
else {
// Adding commas to the output
output += temp[index]+",";
}
index--;
}
alert(output);

Ho do I split these 2 string using Regex? [closed]

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 2 years ago.
Improve this question
Following are 2 strings:
" at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)"
" at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22"
How do I split them to these using JS and Regex?
['callback', '/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js', '541', '21']
['', '/Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js', '269', '22']
try regexp named groups
https://github.com/tc39/proposal-regexp-named-groups
it adds result readability for such strange regexes ;)
const strings = [
" at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)",
" at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22"
];
const regex = /^\s*?at\s?(?<source>.*?)\s\(?(?<path>.*?):(?<row>\d*):(?<column>\d*)/;
strings.forEach(string => {
const result = string.match(regex);
resultElement.innerHTML +=
'\n' + JSON.stringify({string, "result.groups": result.groups}, null, 4)
})
<pre id="resultElement"/>
You can use regex for such purpose, i.e:
const regex = /at( (?:[a-z]+)?)\(?(.+)\:(\d+)\:(\d+)\)?/;
//const str = " at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)";
const str = " at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22";
const found = str.match(regex);
found.splice(0, 1)
console.log(found)
It works for both strings!
I've wrote simple parse function for you:
function parse(string) {
const functionName = string.match(/at .* /);
return [
...(functionName && [functionName[0].slice(2).trim()] || ['']),
...string.match(/\/.*/)[0].split(':')
];
}
First of all I try to extract function name. If it exists I remove 'at' word and use trim function to remove unnecessary spaces. Then I look for substring beginning with slash '/' and match every character after it. Last step is to split returned string.
I believe it matches your requirements.
I've also prepared demo in stackblitz: https://stackblitz.com/edit/js-ol22yf

How to remove extra occurrences of a letter in a string? [closed]

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 3 years ago.
Improve this question
Using Javascript is there a way to remove extra occurrences of a specific letter in a string?
For example:
remove_extra('a', 'caaaat')
//=> 'cat'
I know there must be a brute force way to do something like this but is there an elegant way? I'm not sure how to approach this algorithm.
you can do this with regex:
var test = "aaabbbccc";
console.log(test.replace(/(.)(?=.*\1)/g, "")); //would print abc
var test2 = "caaaaat";
console.log(test2.replace(/(.)(?=.*\1)/g, "")); //would print cat
Sorry, I misunderstood your question.
To only keep one instance of specified char:
function onlyOneCharOf(string, pattern) {
let first = true;
//if (pattern.length !==1) throw Error("Expected one character");
pattern=pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); //escape RegEx special chars
return string.replace(new RegExp(pattern, "g"), value => {
if (first) {
first = false;
return value;
}
return "";
});
}
console.log(onlyOneCharOf("zzzzzaaabbbbcccc", "a"));
Note: the pattern given to the function is used to create a RegEx. Since some characters are special characters, those characters must be escaped. I updated the function to do that for you. You might also want to check the length, but the length might be larger than 1 for some unicode code points.
If you only want any character to appear once, you can use a Set:
function unique(string) {
return Array.from(new Set(string.split(''))).join('');
}
console.log(unique("caaaat"));
A value in a Set may only occur once.
You can use Array.from to explode a string:
Array.from('caaaat');
//=> ["c", "a", "a", "a", "a", "t"]
You can then use Array#filter to keep everything that is neither "a" nor the first occurrence of "a":
Array.from('caaaat').filter((x, i, xs) => x !== 'a' || xs.indexOf(x) === i).join('');
//=> "cat"
(I leave it to you as an exercise to put this into a reusable function.)
Just be aware that if you choose to interpret char as a regular expression without validating it first, you may have unexpected results:
function onlyOneCharOf(string, char) {
let first = true;
return string.replace(new RegExp(char, "g"), value => {
if (first) {
first = false;
return value;
}
return "";
});
}
onlyOneCharOf('caaat', '.');
//=> "c"
onlyOneCharOf('caaat', '?');
//=> SyntaxError

Regular expression for remove last n characters [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a requirement to remove last n characters from string or remove 'page' from a particular string.
Eg:
var string = 'facebookpage';
Expected output string = 'facebook'
I would like to remove 'page' from the string.
Done it using substring.
var str = "facebookpage";
str = str.substring(0, str.length - 4);
Could you help me to find some better way to do it.
Regex for this:
//str - string;
//n - count of symbols, for return
function(str, n){
var re = new RegExp(".{" + n + "}","i");
return str.match(re);
};
EDIT:
For remove last n characters:
var re = new RegExp(".{" + n + "}$","i");
return str.replace(re, "");
UPDATE:
But use regex for this task, not good way; For example, AVG Runtime for 100000 iterations:
Str length solution = 63.34 ms
Regex solution = 172.2 ms
Use javascript replace function
var str = "facebookpage";
str = str.replace('page','');
You can use this regular expression :
(.*)\\w{4}
code :
var regex =(new RegExp("(.*)\\w{4}"))
val output = regex .exec("facebookpage")
// output is : ["facebookpage", "facebook"]
// output[1] is the Expected output which you want.
Hope this helps.

Categories

Resources