Replace the special character and space from the string in javascript - javascript

I have a below string. I need to remove all the special character and space.
var Uid = "s/Information Needed1-s84102-p306";
I tried the below code.It didn't replace the space from the string.
console.log(Uid.replace(/[^\w\s]/gi, '')}")
The output is:- sInformation Needed1s84102p306
I want the output as sInformationNeeded1s84102p306

Simply try using
/[\W_]/g
\W match any non-word character [^a-zA-Z0-9_]
Included _ if you also want to remove it then
Regex

You can just use:
console.log(Uid.replace(/\W+/g, '')}")
\W will match any non-word character including a space.
RegEx Demo

You can use this expression for your case
var x = "s/Information Needed1-s84102-p306";
console(x.replace(/[^A-Z0-9]/ig, ""));
Here is the working Link

Related

regex remove all non alphanumeric except #

How do I remove all non-alphanumeric characters except for #?
`#some random text goes here %#KG§ blah`.replace(/\W/g, ``) // replaces all non-alphanumeric but need to keep the #
/[^a-z0-9#]*/g should work for your case.
console.log(`#some random text goes here %#KG§ blah`.replace(/[^a-z0-9#]*/g, ``))
Quick explaniation
We're picking anything that is alphanumeric or '#' and picking any number of them using '*', then the '^' acts as a not.
I often use this site to test my regexp https://regex101.com/
Use a negated character class that lists # and word chars \w:
console.log('#some random text goes here %#KG§ blah'.replace(/[^#\w]/g, ''));
let str = 'I contains invalid char ##_&';
str.replace((/[^#a-z0-9]+/gi), '');
Please Note that some answers here won't replace something like underscores _
E.g
str.replace(/[^#\w]/g, ''))
Because \w matches underscores

regex custom lenght but no whitespace allowed [duplicate]

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

How to trim all non-alphanumeric characters from start and end of a string in Javascript?

I have some strings that I want to clean up by removing all non-alphanumeric characters from the beginning and end.
It should work on these strings:
)&*#^#*^#&^%$text-is.clean,--^2*%#**)(#&^ --->> text-is.clean,--^2
-+~!##$%,.-"^&example-text#is.clean,--^#*%#**)(#&^ --->> example-text#is.clean
I have this regex, which removes them from the whole string:
val.replace(/[^a-zA-Z0-9]/g,'')
How would I change it to only remove from the beginning and end of string?
Modify your current RegExp to specify the start or end of string with ^ or $ and make it greedy. You can then link the two together with an OR |.
val.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g, '');
This can be simplified to a-z with i flag for all letters and \d for numbers
val.replace(/^[^a-z\d]*|[^a-z\d]*$/gi, '');
You need to use anchors - ^ and $. And also, you would need a quantifier - *:
val.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g,'')
Use anchors to match the start and end of the string:
val.replace(/^[^A-Z0-9]+|[^A-Z0-9]+$/ig, '')
Use anchors ^ and $ to match positions before first character and after last character in the string.
val.replace(/(^[^A-Za-z0-9]*)|([^A-Za-z0-9]*$)/g, '');
You can also shorten your code using \W which means non-alphanumeric character, shortcut for [^a-zA-Z0-9_] in case you want to keep underscore as well.
val.replace(/(^\W*)|(\W*$)/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, '')

Finding Plus Sign in Regular Expression

var string = 'abcd+1';
var pattern = 'd+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
I found out last night that if you try and find a plus sign in a string of text with a Javascript regular expression, it fails. It will not find that pattern, even though it exists in that string. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?
Plus is a special character in regular expressions, so to express the character as data you must escape it by prefixing it with \.
var reg = /d\+1/;
\-\.\/\[\]\\ **always** need escaping
\*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?]
But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.
A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).
Don't escape a letter or digit unless you mean it.
Just a note,
\ should be \\ in RegExp pattern string, RegExp("d\+1") will not work and Regexp(/d\+1/) will get error.
var string = 'abcd+1';
var pattern = 'd\\+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
//3
You should use the escape character \ in front of the + in your pattern. eg. \+
You probably need to escape the plus sign:
var pattern = /d\+1/
The plus sign is used in regular expressions to indicate 1 or more characters in a row.
It should be var pattern = '/d\\+1/'.
The string will escape '\\' as '\' ('\\+' --> '\+') so the regex object init with /d\+1/
if you want to use + (plus sign) or $ (sigil /dollar sign), then use \ (backslash) as a prefix. Like that:
\$ or \+

Categories

Resources