Remove empty values from comma separated string javascript - javascript

How do I remove empty values from an comma separated string in JavaScript/jQuery?
Is there a straightforward way, or do I need to loop through it and remove them manually?
Is there a way to merge all the splits (str and str1) in JavaScript/jQuery?
CODE:
var str = '+ a + "|" + b';
var str1 = '+ a + "-" + b';
str = str.split("+").join(",").split('"|"').join(",");
str1 = str1.split("+").join(",").split('"-"').join(",");
console.log(str); //, a , , , b
console.log(str1); //, a , , , b
EXPECTED OUTPUT :
a,b
Help would be appreciated :)

As I see it, you want to remove +, "|", "-" and whitespace from the beginning and end of the string, and want to replace those within the string with a single comma. Here's three regexes to do that:
str = str.replace(/^(?:[\s+]|"[|-]")+/, '')
.replace(/(?:[\s+]|"[|-]")+$/, '')
.replace(/(?:[\s+]|"[|-]")+/g, ',');
The (?:[\s+]|"[|-]") matches whitespace or pluses, or "|" or "-". The + at the end repeats it one or more times. In the first expression we anchor the match to the beginning of the string and replace it with nothing (i.e. remove it). In the second expression we anchor the match to the end of the string and remove it. And in the third, there is no anchor, because all matches that are left have to be somewhere inside the string - and we replace those with ,. Note the g modifier for the last expression - without it only the first match would be replaced.

The other answer is useful, and may be exactly what you are looking for.
If, for some reason, you still want to use split, luckily that method takes a regex as separator, too:
str = str.split(/\s*\+\s*(?:"\|"\s*\+\s*)?/).slice(1).join(",");
str1 = str1.split(/\s*\+\s*(?:"-"\s*\+\s*)?/).slice(1).join(",");
Because you have a plus sign in front of the "a", you can slice the array to return only the elements after it.
Also, since you mentioned you were new to regular expressions, here is the explanation:
any amount of space
a plus sign
any amount of space
optional (because of the ? after the group, which is the parentheses): a non-capturing (that is what the ?: means) group containing:
"|"
any amount of space
another plus sign
any amount of space

Works perfectly fine:
str.split(/[ ,]+/).filter(function(v){return v!==''}).join(',')

Related

How to replace all \n with space? [duplicate]

I have a var that contains a big list of words (millions) in this format:
var words = "
car
house
home
computer
go
went
";
I want to make a function that will replace the newline between each word with space.
So the results would something look like this:
car house home computer go went
You can use the .replace() function:
words = words.replace(/\n/g, " ");
Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.
Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.
let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");
console.log("After:");
console.log(words);
In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use
var new_words = words.replace(/[\r\n]+/g," ");
See regex demo
To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:
[ - start of a positive character class matching any single char defined inside it:
\r - (\x0D) - \n] - a carriage return (CR)
\n - (\x0A) - a line feed character (LF)
\x0B - a line tabulation (LT)
\x0C - form feed (FF)
\u0085 - next line (NEL)
\u2028 - line separator (LS)
\u2029 - paragraph separator (PS)
] - end of the character class
+ - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
/g - find and replace all occurrences in the provided string.
var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Some simple solution would look like
words.replace(/(\n)/g," ");
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')

Escape / in .split()

Need to escape / in javascript .split() function but cannot seem to figure out!
input -> string "07777/25555,00255" or any of 0777/2555 0777,2555
output -> array {07777,25555,00255}
var p = item.gdp.split(/ , | \//);
Not really good with regex!
What this does is split on either " , " or " /" (note the space characters: space comma space and space forward slash). Your regular expression is absolutely fine if that's what you're intending to replace on.
Here's a Regexper visualisation:
Update
There are no spaces in your string at all, so you need to remove those:
item.gdp.split(/,|\//);
With this, your result will be:
["07777", "25555", "00255"]
A more practical regular expression to use though would be /[,\/] - the square brackets will match on any character held within them.
var item={gdp:"07777/25555,00255"};
var p = item.gdp.split(/[,/]/);
document.write(p[0] + "<br>" + p[1] + "<br>" + p[2]);
07777
25555
00255
Here's one
split(/\s*[,\/]\s*|\s+/);
If you are splitting on only comma and slash as in your first string
"07777/25555,00255"
you can simply split on the character class containing those two characters [,/]
Within a character class the slash does not need to be escaped, so the resulting statement would be
var p = item.gdp.split(/[,/]/);
If you also want to split on space, as in your other example 0777/2555 0777,2555 simply add space to the character class:
var p = item.gdp.split(/[, /]/);
or to split on any whitespace (space, tab, etc.) use the predefined \s:
var p = item.gdp.split(/[,\s/]/);
Further, you can collapse multiple whitespace, but then you need to go beyond a simple character class. Compare...
var str="07777/25555,00255 0777,3444";
// split on white, comma, or slash. multiple spaces causes multiple results
str.split(/[\s,/]/)
// -> ["07777", "25555", "00255", "", "", "", "", "0777", "3444"]
// split on multiple whitespace, OR on comma or slash
str.split(/\s+|[,/]/)
// -> ["07777", "25555", "00255", "0777", "3444"]
input.split(/[\/\s,]+/)
Is this what you are looking for?

How to check if a string has more than one of a certain character in a row in Javascript

I have a string that might have multiple commas in a row. I want to find every time it has more than one comma, I want it to be replaced with only one comma. How can I do this?
Thanks
Use a regular expression:
To test if a string contains multiple commas in a row:
var result = /,,/.test(input);
To replace them with just one:
var result = input.replace(/,+/g, ',');
To replace two or more consecutive commas with a single comma, you can use this:
str = str.replace(/,{2,}/g, ",");
The {2,} after the comma means two or more of whatever the preceeding character was in the regex.
The g flag tells it to replace all occurrences of that in the string.
Working demo: http://jsfiddle.net/jfriend00/pxhLH/
Use a simple loop and replace. Plug this into your page to see it work.
var str = ",,, I have ,, some extra ,, commas ,,";
while (str.indexOf(",,") > -1) {
str = str.replace(",,", ",")
}
alert(str);
The only part you need is the while loop. If you want you can make it into a function where str is the parameter and then kick out your new string.

Remove last appeared comma in string using javascript

I have a text
test, text, 123, without last comma
I need it to be
test, text, 123 without last comma
(no comma after 123). How to achieve this using JavaScript?
str.replace(/,(?=[^,]*$)/, '')
This uses a positive lookahead assertion to replace a comma followed only by non-commata.
A non-regex option:
var str = "test, text, 123, without last comma";
var index = str.lastIndexOf(",");
str = str.substring(0, index) + str.substring(index + 1);
But I like the regex one. :-)
Another way to replace with regex:
str.replace(/([/s/S]*),/, '$1')
This relies on the fact that * is greedy, and the regex will end up matching the last , in the string. [/s/S] matches any character, in contrast to . that matches any character but new line.

How to replace last matched character in string using javascript

i want to replace last input character from keyboard to ''
My String Input are
sample string
"<p><strong>abscd sample text</strong></p>"
"<p>abscd sample text!</p>"
My last character is dynamic that can be any thing between
a to z, A to Z, 0 to 9, any special characters([~ / < > & ( . ] ).
So i need to replace just that character
for example in Sample 1 i need to replace "t" and in sample 2 in need to replace "!"
I tried below code. but it id not worked for me
var replace = '/'+somechar+'$/';
Any way to do it?
Step one
to replace the a character in a string, use replace() function of javaScript. Here is the MDN specification:
Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
Step two
you need to location the character to be replaced through regular expression. You want to replace the last character of a string and this could be expressed as /(.+)(.)$/. . stands for any character, + means more than one character. Here (.+) matches all the character before the last one. (.) matches the last character.
What you want to replace is the one inside the second brackets. Thus you use the same string matched in the first bracket with $1 and replace whatever after it.
Here is the code to realize your intention:
text = 'abscd sample text';
text.replace(/(.+)(.)$/, '$1!');
Do you really need to use regular expressions? How about str = str.slice(0, -1); ? This will remove the last character.
If you need to replace a specific character, do it like this:
var replace = new RegExp(somechar + '$');
str = str.replace(replace, '');
You cannot use slashes in a string to construct a RegEx. This is different from PHP, for example.
I dont really understand which character you want to replace to what, but i think, you should use replace() function in JS: http://w3schools.com/jsref/jsref_replace.asp
string.replace(regexp/substr,newstring)
This means all keyboard character:
[\t\n ./<>?;:"'`!##$%^&*()[]{}_+=-|\\]
And this way you can replace all keyboard character before < mark to ""
string.replace("[a-zA-Z0-9\t\n ./<>?;:"'`!##$%^&*()[]{}_+=-|\\]<","<")

Categories

Resources