Remove last appeared comma in string using javascript - 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.

Related

regex replace certain character but not for particular set in javascript

var str='select * from where item1=abcd and price>=20';
I am using the below code to replace the '=' to empty space
str=str.replace(/[=]/g, " ")
but it is also replacing '>=' . I want >= not to be replaced with any thing and also for some others condition like '==' or '<=' etc.
So my output should be - 'select * from where item abcd and price>=20'
Please help me to achieve this.
Use below regex for replacement
/([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi
and replace it with $1 $2.
([a-z0-9]+): Match one or more alphanumeric characters and add them to capturing group
\s*: Zero or more space characters
=: Equal sign
gi: g: Global flag to match all possible matches. i: Case-insensitive flag.
$n in the replacement part is the nth captured group value.
var regex = /([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi;
var str = 'select * from where item1=abcd and price>=20';
console.log(str.replace(regex, '$1 $2'));
Replace an equal sign with a letter or number on either side with the corresponding characters around a space.
str.replace(/([a-zA-Z0-9])=([a-zA-Z0-9])/, '$1 $2')
In regex [] means "the set of", so [a-zA-Z0-9] is one character from the set of any lowercase, uppercase, or digit.
Simple and dirty trick. Remove g from regx
var str='select * from where item1=abcd and price>=20';
console.log(str.replace(/[=]/, " "))
A good way to approach these problems is to capture everything you wish to skip, and then not capture everything you wish you remove. In your case:
(>=|<=|==|'[^']*(?:''[^']*)*')|=
and replace with $1.
Working example: https://regex101.com/r/3pT9ib/3
First we have a capturing group: (...), which is captured into $1.
The group matched >= and <=. I also threw in == (is this valid in SQL?) and escaped SQL strings, just for the example.
If we were not able to match the group, we can safely match and remove the leftover =.
This approach is explained nicely here: Regex Pattern to Match, Excluding when... / Except between

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', ' ')

Remove empty values from comma separated string 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(',')

RegEx that will match the last occurrence of dot in a string

I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
I need to use a regex to replace the last occurrence of the dot with another string like #2x and then the dot again (very much like a retina image filename) i.e.:
tro.lo.png -> tro.lo#2x.png
Here's what I have so far but it won't match anything...
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " #2x.");
any suggestions?
You do not need a regex for this. String.lastIndexOf will do.
var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + "#2x" + str.substr(i);
}
See it in action.
Update: A regex solution, just for the fun of it:
str = str.replace(/\.(?=[^.]*$)/, "#2x.");
Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.
Just use special replacement pattern $1 in the replacement string:
console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "#2x.$1"));
// "tro.lo.lo.lo.lo.lo#2x.png"
You can use the expression \.([^.]*?):
str.replace(/\.([^.]*?)$/, "#2x.$1");
You need to reference the $1 subgroup to copy the portion back into the resulting string.
working demo http://jsfiddle.net/AbDyh/1/
code
var str = 'tro.lo.lo.lo.lo.lo.zip',
replacement = '#2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');
$('.test').html(str);
alert(str);​
To match all characters from the beginning of the string until (and including) the last occurence of a character use:
^.*\.(?=[^.]*$) To match the last occurrence of the "." character
^.*_(?=[^.]*$) To match the last occurrence of the "_" character
Use \. to match a dot. The character . matches any character.
Therefore str.replace(/\.([^\.]*)$/, ' #2x.').
You could simply do like this,
> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1#2x");
'tro.lo.lo.lo.lo.lo#2xzip'
Why not simply split the string and add said suffix to the second to last entry:
var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '#2x';
var newString = arr.join('.');
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.#x2$2")

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