Replace multiple spaces, multiple occurrences of a comma - javascript

I am trying to clean an input field client side.
Current Value
string = 'word, another word,word,,,,,, another word, ,,;
Desired Value after cleaning
string = 'word,another word,word,another word;
Simplified version of what I have tried http://jsfiddle.net/zg2e7/362/

You can use
var str = 'word,word,word,,,,,new word, , another word';
document.body.innerHTML = str.replace(/(?:\s*,+)+\s*/g, ',');
You need to use g modifier to find and replace all instances
You need to also match optional whitespace between commas and on both sides of them.
Regex explanation:
(?:\s*,+)+ - 1 or more sequences of
\s* - 0 or more whitespace characters
,+ - 1 or more commas.

string = 'word, another word,word,,,,,, another word, ,,';
console.log(string.replace(/(,)[,\s]+|(\s)\s+/g ,'$1').replace(/^,|,$/g,''));

Try using split and trim and map and join rather than regex being that regex can be a bit clunky.
$.map(str.split(','),function(item,i){
if(item.trim()){
return item.trim()
}
}).join(',')
So split the string by the , and then use the map function to combine them. If the item has value after being trimmed then keep the value. Then after it has been mapped to a array of the valid values join them with a comma.

Related

Capture quoted string in comma separated string using regular expression

I am trying to match all the string withing double quotes which is separated by comma
For eg in the sample string
"COUNT","count(1)","crmuser.accounts"
i want to match
COUNT
count(1)
crmuser.accounts
Regular expression (?<=").*?(?=") is matching the comma seperator as well which is not required. How can i exclude commas in the string.
There are a few different workarounds you could use for this; for example using capture groups as suggested in the comments by The fourth bird. But for me personally, I try to avoid using .*.
For this type of example, I would honestly recommend just using a character set of valid characters you will use and looking for more than one character (2 or more) because you will effectively skip lone separators such as a single ,. You can even add a comma to that character set and it will still work.
(?<=")[\w\(\)\.,]{2,}(?=")
Demo
For this format of string you could just use :
var str = '"COUNT","count(1)","crmuser.accounts"' ;
var separated = str.split('","') ;
for(var i in separated){
i.replace('"','') ;
} ;

How to replace matched characters with a same number of spaces

I am using javascript and looking for a regex which can replace a matched string with the same number of space. For example, I want to match a string which begins with show and ends to the end of line, this is the regex I am using /show .*$/. If users type show dbs then I want to replace with (8 spaces). How can I know the number of characters for the matched string?
I believe the most concise way to achieve such results in javascript with RegEx is to match one part of the string, replace the rest with spaces and concatenate both parts as follows:
str.replace(/^(show)(.*)/, (str, p1, p2) => p1 + p2.replace(/./g, " "));
The first replace will separate the beginning from the end and send those parts as arguments into the method. The first part can be left untouched and the second part transformed into spaces.
you can use .length on the matched element. For example
var pat = /show .*$/
'show dbs'.match(pat)[0].length
will return 8 then you can either concatenate the returned value or use .replace() on it
'show dbs'.replace(/^/, " ".repeat(8)) //we got 8 from the length property
Note: if there are multiple matches you'll have to loop over them

Escape single backslash inbetween non-backslash characters only

I have some input coming in a web page which I will re display and submit elsewhere. The current issue is that I want to double up all single backslashes that are sandwiched inbetween non-backslash characters before submitting the input elsewhere.
Test string "domain\name\\nonSingle\\\WontBe\\\\Returned", I want to only get the first single backslash, between domain and name.
This string should get nothing "\\get\\\nothing\\\\"
My current pattern that I can get closest with is [\w][\\](?!\\) however this will get the "\n" from the 1st test string i have listed. I would like to use lookbehind for the regex however javascript does not have such a thing for the version I am using. Here is the site I have been testing my regexs on http://www.regexpal.com/
Currently I am inefficiently using this regex [\w][\\](?!\\) to extract out all single backslashes sandwiched between non-backslash characters and the character before them (which I don't want) and then replacing it with the same string plus a backslash at the end of it.
For example given domain\name\\bl\\\ah my current regex [\w][\\]\(?!\\) will return "n\". This results in my code having to do some additional processing rather than just using replace.
I don't care about any double, triple or quadruple backslashes present, they can be left alone.
For example given domain\name\\bl\\\ah my current regex [\w][\\]\(?!\\) will return "n\". This results in my code having to do some additional processing rather than just using replace.
It will do just using replace, since you can insert the matched substring with $&, see:
console.log(String.raw`domain\name\\bl\\\ah`.replace(/\w\\(?!\\)/g, "$&\\"))
Easiest method of matching escapes, is to match all escaped characters.
\\(.)
And then in the replacement, decide what to do with it based on what was captured.
var s = "domain\\name\\\\backslashesInDoubleBackslashesWontBeReturned";
console.log('input:', s);
var r = s.replace(/\\(.)/g, function (match, capture1) {
return capture1 === '\\' ? match : '$' + capture1;
});
console.log('result:', r);
The closest you can get to actually matching the unescaped backslashes is
((?:^|[^\\])(?:\\\\)*)\\(?!\\)
It will match an odd number of backslashes, and capture all but the last one into capture group 1.
var re = /((?:^|[^\\])(?:\\\\)*)\\(?!\\)/g;
var s = "domain\\name\\\\escapedBackslashes\\\\\\test";
var parts = s.split(re);
console.dir(parts);
var cleaned = [];
for (var i = 1; i < parts.length; i += 2)
{
cleaned.push(parts[i-1] + parts[i]);
}
cleaned.push(parts[parts.length - 1]);
console.dir(cleaned);
The even-numbered (counting from zero) items will be unmatched text. The odd-numbered items will be the captured text.
Each captured text should be considered part of the preceding text.

Regex get inconsistent length of string's value

2f34435-something.jpg
4t44234-something.jpg
5465g67-something.jpg
says I have 3 string above, without using split, how can I do regex to get the value before dash? the length of strings is not consistent though..
One option would be to match one or more non-dash characters at the beginning of the string:
^[^-]+
^ - Anchor that denotes the beginning of the string
[^-] - Character set to match all characters that are not dashes.
+ - One or more occurrences of non-dash characters.
For instance:
'2f34435-something.jpg'.match(/^[^-]+/);
// ["2f34435"]
With the .split() method, you would just need to retrieve the first match:
'2f34435-something.jpg'.split('-')[0];
// "2f34435"
you can use...
/^(.+?)-/gm
which will capture all 3 ( or as many as you have )
You can see it in action here https://regex101.com/r/gD5sU2/2
This will also handle if you get - in the rest of the filename...
such as :-
2f34435-something-else.jpg
4t44234-something.jpg
5465g67-something.jpg
([a-z0-9]+)-[a-z0-9]+.jpg matches each of those strings and the string returned from the first group will match the text before the dash.
Use look ahead for to do it
/^.+?(?=-)/gm
https://regex101.com/r/mW5bO7/2

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.

Categories

Resources