Trim last + from string in jQuery - javascript

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.

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

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

Regex for both newline and backslash for Replace function

I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');

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