Regex replace linebreak and comma - javascript

i've a question about regex, i've a text and it looks like below :
car,model,serie
,Mercedes,324,1,
,BMW,23423,1,
,OPEL,54322,1,
it should look like:
car,model,serie
Mercedes,324,1,
BMW,23423,1,
OPEL,54322,1,
so without commas at the beginning of the text.
What i tried :
var str2 = str.replace(/\n|\r/g, "");
but somehow, i couldn't add comma in regex.
can anyone help me?
Thanks in advance.

There have been a lot of responses to this question and for a newbie to regex it is probably a bit overwelming,
Overall the best response has been:
var str2 = str.replace(/^,/gm, '');
This works by using ^, to check if the first character is a comma and if it is, remove it. It also uses the g and m flags to do this for the first character of every line.
If you are curious about the other versions then read on:
1:
var str2 = str.replace(/^,+/gm, '');
This is a slight variant in that it will remove multiple consecutive commas at the beginning of each line, but based off of your dataset this is not required.
2:
var str2 = str.replace(/\n,/g, '\n');
This version works exactly the same as the first, however it finds each newline follow by a comma with \n, and replaces it with another newline.
3:
var str2 = str.replace(/(\n|\r),/g, '$1')
This version is the same as the previous however it doesn't make the assumption that the newline is a \n, it instead captures any newlines or carriage returns, it works the same as the m flag and ^,.
4:
var str2 = str.replace(/\n+|\r+|,+/g,"\n")
And finally there is this, this is a combination of all the previous regex's, it makes the assumption that you may have a lot mixed newlines and commas without any text, and that you would want to remove all of those characters, it is unnecessary for your examples.

Use this syntax:
str.replace(/^,/gm, '');

You can just use multiline flag and replace leading commas:
str = str.replace(/^,+/gm);
RegEx Demo

Try:
var str2 = str.replace(/(\n|\r),/g, '$1')
Your comma was actually placed outside the regex pattern, so you weren't far off :)

Related

RegEx issue in JavaScript Function - Not replacing anything

Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.
function returnFloat(str){
console.log(str.replace(/$,)( /g,""));
}
but when I call it:
returnFloat("($ 51,453,042.21)")
>>> ($ 51,453,042.21)
It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.
My plan B is ugly:
str = str.replace("$", "");
str = str.replace(",", "");
str = str.replace(",", "");
str = str.replace(" ", "");
str = str.replace("(", "");
str = str.replace(")", "");
console.log(str);
There are certain things in RegEx that are considered special regex characters, which include the characters $, ( and ). You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter
function toFloat(str){
return str.replace(/[\$,\(\)]/g,'');
}
console.log(toFloat('($1,234,567.90'));
Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.
the $ character means end of line, try:
console.log(str.replace(/[\$,)( ]/g,""));
You can fix your replacement as .replace(/[$,)( ]/g, "").
However, if you want to remove all letters that are not digit or dot,
and easier way exists:
.replace(/[^\d.]/g, "")
Here \d means digit (0 .. 9),
and [^\d.] means "not any of the symbols within the [...]",
in this case not a digit and not a dot.
if i understand correctly you want to have this list : 51,453,042.21
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21
if you want to delete ','
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21

Trim last + from string in jQuery

I'm trying to generate a link using jQuery and need to trim the last '+' sign off the end. Is there a way to detect if there is one there, and then trim it off?
So far the code removes the word 'hotel' and replaces spaces with '+', I think I just need another replace for the '+' that shows up sometimes but not sure how to be super specific with it.
var nameSearch = name.replace("Hotel", "");
nameSearch = nameSearch.replace(/ /g, "+");
Thanks
You could simply use String.prototype.trim() before you call replace, in order to remove the leading and trailing white-space from the String:
var nameSearch = name.trim().replace("Hotel", "").replace(/ /g, "+");
References:
String.prototype.trim().
You can target the end of the string within a Regex with the $ character. You can remove the + signs from the end like this.
nameSearch = nameSearch.replace(/\+*$/g, "");
But even better, as David Thomas pointed out, you should call trim on the string before your manipulation, so it won't have any leading and trailing white-spaces, hence you won't need to trim the + signs.

Replacing, regex, javascript

Got this string:
'test',$, #207
I need to remove spaces which have a commma before
So the result will be: 'test',$,#207
Tried this:
replace(/\/s,]/g, ',')
Not working. Any ideas?
To replace only spaces and not other whitespaces use the following regex.
Regex: /, +/g
Explanation:
, will search for comma.
+ will search for multiple spaces.
And then replace by , using replace(/, +/g, ',')
Regex101 Demo
JSFiddle demo
Since your pattern is simple you can just do this .split(', ').join(',')
I need to remove spaces which have a commma afterwards
No, your example says the opposite. That is, you want to remove spaces that have a comma before them.
In either case, the error in your expression is the "]".
replace(/\/s,/g, ',')
Does what you say you want to do, and
replace(/,\/s/g, ',')
Does what the example says.
The other answer is right, though - just use replace(' ,', ''); you need no regex here.
I think you meant comma that have whitespace afterwards:
stringVar = "'test',$, #207";
replace('/\,\s/g', stringVar);
\, means , literally and \s means whitespace.
You can test javascript regex and know a little more about the modifiers and stuff at regex101.
replace(new RegExp(find, ', '), ',');
For all whitespaces which have a "," before
var str = "test,$, #207, th, rtt878";
console.log(str.replace(/\,\s+/g,","));
var str = "test,$, #207";
console.log(str.replace(/\,\s+/g,","));

Javascript: regex escaped space

I have a directory with space on unix, so the space is backslashed. And I need to replace the backslashed space with semicolon. Tried multiple regex'es but not able to find the answer
var str = '/test\ space/a.sh -pqr';
So I am looking to get this after the replace /test;space/a.sh -pqr
console.log("replace: ", str.replace(/\\\s+/g, ";")); //This one doesn't work, (formatting is taking out one backslash)
Your regular expression is correct.
It's your example string that is incorrect - the \ is not properly escaped:
var str = '/test\\ space/a.sh -pqr';
See the fiddle and read more special characters in JavaScript strings.

Is there a JavaScript regular expression to remove all whitespace except newline?

How do I remove white spaces in a string but not new line character in JavaScript. I found a solution for C# , by using \t , but it's not supported in JavaScript.
To make it more clear, here's an example:
var s = "this\n is a\n te st"
using regexp method I expect it to return
"this\nisa\ntest"
[^\S\r\n]+
Not a non-whitespace char, not \r and not \n; one or more instances.
This will work, even on \t.
var newstr = s.replace(/ +?/g, '');
Although in Javascript / /g does match \t, I find it can hide the original intent as it reads as a match for the space character. The alternative would be to use a character collection explicitly listing the whitespace characters, excluding \n. i.e. /[ \t\r]+/g.
var newString = s.replace(/[ \t\r]+/g,"");
If you want to match every whitespace character that \s matches except for newlines, you could use this:
/[\t\v\f\r \u00a0\u2000-\u200b\u2028-\u2029\u3000]+/g
Note that this will remove carriage returns (\r), so if the input contains \r\n pairs, they will be converted to just \n. If you want to preserve carriage returns, just remove the \r from the regular expression.
Try this
var trimmedString = orgString.replace(/^\s+|\s+$/g, '') ;
This does the trick:
str.replace(/ /g, "")
and the space does NOT match tabs or linebreaks (CHROME45), no plus or questionmark is needed when replacing globally.
In Perl you have the "horizontal whitespace" shorthand \h to destinguish between linebreaks and spaces but unfortunately not in JavaScript.
The \t shorthand on the other hand IS supported in JavaScript, but it describes the tabulator only.
const str = "abc def ghi";
str.replace(/\s/g, "")
-> "abcdefghi"
try this '/^\\s*/'
code.replace(/^\s[^\S]*/gm, '')
works for me on text like:
#set($todayString = $util.time.nowEpochMilliSeconds())
#set($pk = $util.autoId())
$util.qr($ctx.stash.put("postId", $pk))
and removes the space/tabs before the first 3 lines with removing the spaces in the line.
*optimisation by #Toto:
code.replace(/^\s+/gm, '')

Categories

Resources