regex to remove multiple comma and spaces from string in javascript [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string like
var str=" , this, is a ,,, test string , , to find regex,,in js. , ";
in which there are multiple spaces in beginning,middle and end of string with commas. i need this string in
var str="this is a test string to find regex in js.";
i found many regex in forum removing spaces , commas separately but i could not join them to remove both.
Please give explanation of regex syntex to if possible .
Thanks in advance

You can just replace every space and comma with space then trim those trailing spaces:
var str=" , this, is a ,,, test string , , to find regex,,in js. , ";
res = str.replace(/[, ]+/g, " ").trim();
jsfiddle demo

you can use reg ex for this
/[,\s]+|[,\s]+/g
var str= "your string here";
//this will be new string after replace
str = str.replace(/[,\s]+|[,\s]+/g, 'your string here');
RegEx Explained and Demo

Try something like this:
var new_string = old_string.replace(/[, ]+/g,' ').trim();
The regex is simply [, ]+ if we were to break this down the \s means ANY whitespace character and , is a literal comma. The [] is a character set (think array) and the + means one or more matches.
We throw in a /g on the end so that it does a global search and replace, otherwise it'd just do it for one match only.

You should be able to use
str.replace(/,/g," ");
The 'g' is the key, you may need to use [,]

Related

Find and replace # mentions using 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 2 years ago.
Improve this question
I'm trying to parse strings to find and replace # mentions.
Here is a sample string:
Hi #jordan123 and #jordan have a good day
I want to find and replace #jordan with #jordananderson without modifying #jordan123
I used this regex to find a list of all of the mentions in the string:
let string = 'Hi #jordan123 and #jordan have a good day'
let result = string.match(/\B\#\w\w+\b/g);
that returns:
['#jordan123', '#jordan']
But I can't figure out how to continue and complete the replacement.
Valid characters for the username are alphanumeric and always start with the # symbol.
So it also needs to work for strings like this:
Hi #jordan123 and #jordan!! have a good day
And this
Hi #jordan123! and !#jordan/|:!! have a good day
My goal is to write a function like this:
replaceUsername(string, oldUsername, newUsername)
If I understand your question correctly, you need \b, which matches a word boundary:
The regex: #jordan\b will match:
Hi #jordan123 and #jordan!! have a good day
Hi #jordan123! and !#jordan/|:!! have a good day
To build this regex, just build it like a string; don't forget to sanitize the input if it's from the user.
var reg = new RegExp("#" + toReplace + "\\b")
In general if you have one string of a found value, and a larger string with many values, including the found value, you can use methods such as split, replace, indexOf and substring etc to replace it
The problem here is how to replace only the string that doesn't have other things after it
To do this we can first look for indexOf the intended search string, add the length of the string, then check if the character after it doesn't match a certain set of characters, in which case we set the original string to the substring of the original up until the intended index, then plus the new string, then plus the substring of the original string starting from the length of the search string, to the end. And if the character after the search string DOES match the standard set of characters, do nothing
So let's try to make a function that does that
function replaceSpecial(original, search, other, charList) {
var index= original.indexOf(search)
if(index > -1) {
var charAfter = original [index + search.length]
if (!charList.includes(charAfter)) {
return original. substring (0, index) + other + original. substring (index+ search.length)
} else return original
} else return original
}
Then to use it with our example
var main ="Hi #jordan123 and #jordan!! have a good day"
var replaced = replaceSpecial (main, "#jordan", "#JordanAnderson", [0,1,2,3,4,5,6,7,8,9])

Split a string using a regex [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like to split the following str into an array that has 2 elements, the first being 'Some words in a sentence', the second being 'ABC' where ABC can be any upper case character.
const str = 'Some words in a sentence (ABC)';
const regex = ?
const arr = str.split(regex);
...
expect(arr[0]).to.eq('Some words in a sentence');
expect(arr[1]).to.eq('ABC');
expect(arr.length).to.eq(2);
Any thoughts would be appreciated.
Cheers,
Paul
The trick with regex is to break it into steps.
You want two elements, that means two groups, e.g. (<-- between these -->))
The easy one is getting the (ABC) at the end -> \((.*?)\)$ (escaped ()'s
And now you can conclude the rest is the other part: (.*?)
Explained:
/---\ is the \((.*?)\)$
Some words in a sentence (ABC)
^---- (.*?) ----^
That should push you in the direction you are looking for, the final part is for you to figure out :)
Goto https://regex101.com/ and try this
/(.*)\(([A-Z]{3})\)/
with your string
'Some words in a sentence (ABC)'
You will get
Match 1
Full match 0-30 `Some words in a sentence (ABC)`
Group 1. 0-25 `Some words in a sentence `
Group 2. 26-29 `ABC`

Get part of the string using regexp [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've a strings, which can have a text like:
'some text user#t12# some text'
'username#John# some text'
'some text usersurname#Malks#'
'userphoto#1.jpg#'
How do I get a text between # and # symbols?
There's a typical structure of the part of the string to search for - type#variable#
type is a JS variable type, it's placed before the first #.
variable is a text that I need to get.
I'm searching for a regexp, that return variable, that is between #...#.
The problem is, I'm not too familiar with regexp, can you help me please?
You need to use capture groups, basically in a regex anything in brackets will be part of the cpature group, in this case you want to capture all the characters between two hashes. The any amount of characters regex is .* so this is what you want to capture between two hashes. Once you execute it you will find the match as second in the array (the first will be the string with the hashes.
var type = "";
var myString = "some text user#t12# some text";
var myRegexp = new RegExp(type+"#(.*)#","g");
var match = myRegexp.exec(myString);
alert(match[1]); // t12
any other matches between hashes will be in match[2].. match[n]

Replace in comma followed by double quotes in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Can anyone tell me how to replace comma followed by double quotes(",) with double quotes(") in java script
Actually I am getting the string as ",4,34,26,23"
but I want to remove the first comma in the string
also the same when it occurs at the last(,") as below
"4,34,23,54,"
Thanks in Advance
Rakesh
You can use regular expressions like this
var data = ",4,34,26,23,";
data = data.replace(/^,|,$/g, "");
console.log(data);
Output
4,34,26,23
If the double quotes are also part of the original string,
var data = "\",4,34,26,23,\"";
data = data.replace(/^",|,"$/g, "");
If you want to strip only the , and retain ", you can just put the double quotes as the second parameter to the replace, as suggested by #nnnnnn, like this
data = data.replace(/^,|,$/g, "\"");
data = data.replace(/^",|,"$/g, "\"");
var a = ",4,34,26,23";
var replaced=a.replace(',','');
alert(replaced);
Try this
var x = ',4,34,26,23';
x.replace(/^,|,$/g,'');
This removes any starting or ending commas :
",4,34,26,23,".replace(/^,|,$/g,"") // "4,34,26,23"
try this
var str = '",4,34,26,23"';
str = str.replace('",','"');

Regex that searches for a starting character, anything in between, then an ending character? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So basically, I have a hugeee list of values that I copied from my site and would like them as just plain text. I need to create a regex for Javascript that removes the unwanted stuff
Here is what the values look like before hand:
<option value="111122223333">Some text (45)</option>
<option value="345835385390">Some text (10)</option>
<option value="456727235764">Some text (50)</option>
Here is what they need to look like afterwards:
Some text
Some text
Some text
Is this possible with 1 regex, or will many be needed?
My thinking is that a regex looks for < anything in between, and then > could be used on both the opening and closing option tags. Then the regex could be slightly modified to look for opening ( and then closing ) to remove the counter numbers to the left of the 'Some text' string.
Still learing regex, so it would be great if someone could also add a small explanation to their answer so that I could have some understanding of it. Thanks.
You can probably simplify this if you can use a library like jQuery. In that case you can use the text() method of a jQuery object to get the inner text, then run a simple regex to remove the '(xx)' part:
var vals = $('option').map(function() {
return $(this).text().replace(/\s*\(\d*\)$/, '');
});
// vals => ["some text", "some text", "some text"]
here's a fiddle: http://jsfiddle.net/jhummel/U46pH/
if you can't use a library I think you are looking for a regex like:
/<[^>]+>([^\(]+)\(\d*\)<[^>]+>/g
edit
You asked for a regex explanation, let's look at it part by part
/ = start the regex
< = find a '<' character
[^>]+ = find any character that is not a '>' one or more times
> = find a '>' character
( = start a group, anything in the parens will be saved for later
[^(]+ = find any character that is not a '(' one or more times - need to escape it with a backslash because the paren is a reserved character in regex
) = close the group
( = find a '(' char - need to escape it with a backslash again
\d* = find any numbers zero or more times
) = find a ')' character - escaped again
< = find a '<' character
[^>]+ = find any character that is note a '>' one or more times
> = find a '>' character
/ = end the regex
g = regex flag. Means find all the matches don't stop after the first match
If that's all you hope to accomplish then you can use something like:
(>)(.+)(<)
and then grab the second group out of the match.
EDIT: The parentheses are used to denote groups.

Categories