Replacing, regex, javascript - 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,","));

Related

replace single quote in middle of string using regex

Have a string:
stringName= "'john's example'"
Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript
have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work
Help is very appreciated! :)
Use (^'|'$)|' as matching regular expression:
stringName = "'john's e'xam'ple'";
console.log(
stringName.replace(/(^'|'$)|'/g, '$1')
);
First thing is you aren't doing a regex replace, you are replacing a string which looks like /.'./ (because of the " in the first argument). Secondly, the regex you're doing is only going to be looking for a single character (.) then a single quote, then another character. What you might want to do is something like stringName.replace(/(.+)'(.+)/, "$1$2")
Use split, join after stripping of first and last character
var f1 = (str) => str.charAt(0) + str.split("'").join("") + str.slice(-1);
f1( "'john's exa''mp'le'" ); //'johns example'

Regex replace linebreak and comma

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 :)

jQuery - Replace all parentheses in a string

I tried this:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace("(", "").replace(")", "");
It works for all double and single quotes but for parentheses, this only replaces the first parenthesis in the string.
How can I make it work to replace all parentheses in the string using JavaScript? Or replace all special characters in a string?
Try the following:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
A little bit of REGEX to grab those pesky parentheses.
You should use something more like this:
mystring = mystring.replace(/["'()]/g,"");
The reason it wasn't working for the others is because you forgot the "global" argument (g)
note that [...] is a character class. anything between those brackets is replaced.
You should be able to do this in a single replace statement.
mystring = mystring.replace(/["'\(\)]/g, "");
If you're trying to replace all special characters you might want to use a pattern like this.
mystring = mystring.replace(/\W/g, "");
Which will replace any non-word character.
You can also use a regular experession if you're looking for parenthesis, you just need to escape them.
mystring = mystring.replace(/\(|\)/g, '');
This will remove all ( and ) in the entire string.
Just one replace will do:
"\"a(b)c'd{e}f[g]".replace(/[\(\)\[\]{}'"]/g,"")
That should work :
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
That's because to replace multiple occurrences you must use a regex as the search string where you are using a string literal. As you have found searching by strings will only replace the first occurrence.
The string-based replace method will not replace globally. As such, you probably want to use the regex-based replacing method. It should be noted:
You need to escape ( and ) as they are used for group matching:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
This can solve the problem:
myString = myString.replace(/\"|\'|\(|\)/)
Example

Replace all whitespace characters

I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?
I tried:
str.replace(/ /gi, "X")
You want \s
Matches a single white space
character, including space, tab, form
feed, line feed.
Equivalent to
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
in Firefox and [ \f\n\r\t\v] in IE.
str = str.replace(/\s/g, "X");
We can also use this if we want to change all multiple joined blank spaces with a single character:
str.replace(/\s+/g,'X');
See it in action here: https://regex101.com/r/d9d53G/1
Explanation
/ \s+ / g
\s+ matches any whitespace character (equal to [\r\n\t\f\v ])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Global pattern flags
g modifier: global. All matches (don't return after first match)
\s is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.
str.replace(/\s/g, "X")
Have you tried the \s?
str.replace(/\s/g, "X");
If you use
str.replace(/\s/g, "");
it replaces all whitespaces. For example:
var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
Try this:
str.replace(/\s/g, "X")
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"
You could use the function trim
let str = ' Hello World ';
alert (str.trim());
All the front and back spaces around Hello World would be removed.
Actually it has been worked but
just try this.
take the value /\s/g into a string variable like
String a = /\s/g;
str = str.replaceAll(a,"X");
I've used the "slugify" method from underscore.string and it worked like a charm:
https://github.com/epeli/underscore.string#slugifystring--string
The cool thing is that you can really just import this method, don't need to import the entire library.

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