How to replace multiple characters from text? - javascript

As you can see in my code I am trying to replace some characters! So I want this:
First I remove all "||",
Then I remove all two or more white spaces with one space,
Then I replace all one space with "-"
With my code all two or more spaces are replacing with single space and all single spaces getting replace with "-". But the problem is this "|" is not getting removed. Please help!!
document.getElementById("NormalText").value.replace(/|/g, '').replace(/\s\s+/g, ' ').replace(/ /g, '-');

Your example isn't working because the pipe character has special meaning in regex; it is used for alternation. For example, a|c replaces all instances of a and c:
const myString = "abc";
const result = myString.replace(/a|c/g,"");
console.log(result);
To match a literal | character, escape it with a preceding backslash: \|:
const myString = "my|string";
const result = myString.replace(/\|/g, '');
console.log(result);

You need to escape the pipe symbol like so.
value.replace(/\|/g, '')

Related

How to remove characters in a string that matches a RegEx while preserving spaces?

I am trying to remove characters from a string so that it will match this RegEx: ^[-a-zA-Z0-9._:,]+$. For example:
const input = "test // hello". The expected output would be "test hello". I tried the following:
input.replace(/^[-a-zA-Z0-9._:,]+$/g, "")
But this does not seem to work
The example output "hello world" that you give does not match your regex, because the regex does not allow spaces. Assuming you want to keep spaces, use
input.replace(/[^-a-zA-Z0-9._:, ]/g, "")
The negation character ^ must be inside the [...]. The + is not needed, because /g already ensures that all matching characters are replaced (that is, removed).
If you also want to condense consecutive spaces into a single space (as implied by your example), use
input.replace(/[^-a-zA-Z0-9._:, ]/g, "").replace(/\s+/g, " ")
I like to use the following canonical approach:
var input = "test // hello";
var output = input.replace(/\s*[^-a-zA-Z0-9._:, ]+\s*/g, " ").trim()
console.log(output);
The logic here is to target all unwanted characters and their surrounding whitespace. We replace with just a single space. Then we do a trim at the end in case there might be an extra leading/trailing space.

JavaScript Regex - Remove Whitespace from Start and End

I worked on the below challenge for about 3 hours and none of my code was working. Decided to look at the solution to understand why I was not working. When I looked at the solution I was confused because I thought that \s to identify white spaces not to remove them... can someone give me hand and explain why the usage of \s instead of \S and why using the empty string ("") to get rid of the white spaces on both ends.
CHALLENGE
Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings.
//SOLUTION
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
\s means whitespace characters in regex, like <space>, <tab>, etc.
^ means the beginning of the string
$ means the end of the string
| means OR (match the left side or the right side)
+ means 1 or more (based off of the rule on the left)
/a regex/g the g means "global", aka "match multiple times" since you could need to match at the beginning AND end
So the regex means:
/^\s+|\s+$/g
/ / Wrap the regex (how you do it in JS)
^\s+ Try to match at the beginning one or more whitespace chars
| Or...
\s+$ Try to match whitespace chars at the end
g Match as many times as you can
String.prototype.replace replaces the match(es) found in the regex with the string provided as the 2nd argument, in this case an empty string.
So the process internally is:
Look for all sections that match the regex (which will be the whitespace at the beginning and the whitespace at the end
Replace each match with "", removing those matches entirely
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
console.log('"' + result + '"');
Most people use String.prototype.replaceAll instead of .replace when they use the global flag (
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replaceAll(wsRegex, "");
console.log('"' + result + '"');
The second argument of replace is for what you will replace from the match(es) of the first argument.
The regex will match/select the spaces on the beginning (^) and on the end ($) of the string, and then will be replaced by "".
When you use the regex /(\S)/g you're matching everything but spaces, in this case you will use something like hello.replace(/(\S)/g, '$1');
$1 means the first group of your regex.

How to replace all spaces except spaces inside "a b" in RegEx?

How would I replace all space characters with letter "_" except spaces inbetween characters "a" and "b" like this "a b".
// this is what I have so far to save someone time (that's a joke)
var result:String = string.replace(/ /g, "_");
Oh this is in JavaScript.
Use this:
var result:String = string.replace(/([^a]) | ([^b])/g, "$1_$2");
A simplified explanation of the above is that it replaces a space that either:
is preceded by a character other than a
is followed by a character other than b
Note: to generalize the regex to include tabs and newlines, use \s, like this:
var result:String = string.replace(/([^a])\s|\s([^b])/g, "$1_$2");
Try this regex:
/(?!a)\s(?!b)/g
Edit: This is not the best solution as KendallFrey pointed out.

How to convert a string with regex

How can i convert a string with regex, so that it contains just alphabetical (a-z) or a hyphen.
It should get rid " ' ! ? . and so on. Even if they appear multiple times.
// if i have e.g.
var test = '"test!!!"';
// how can i get the value "test"?
Can sombody help. RegEx is totaly new to me.
Simply replace the characters you don't want:
'"test!!!"'.replace(/[^a-z-]/gi, '')
[^a-z-] matches all characters but a-z and the hyphen. The /g flag makes the regexp apply multiple times. The /i flag (optional) makes it match case-insensitively, i.e. not replace upper-case characters.
That's quite simple: You build a character class that matches everything except those chars you want and remove them by replacing each occurence (global flag) with the empty string:
return str.replace(/[^a-z-]/g, "");
str = "hello!! my + name $ is slim-shady";
console.log(str.replace(/[^a-z-]+/g, ''));
$ node src/java/regex/alphanum.js
hellomynameisslim-shady
Use the replace method for any string variable and specify the characters you wish to remove.
Here's an example:
var sampleString = ("Hello World!!"); //Sample of what you have.
var holdData = sampleString.replace(/!!/gi, '');
window.alert(holdData);
var str = "test!!!";
str = str.replace(/[^A-Za-z\-]/g,"");

jQuery remove special characters from string and more

I have a string like this:
var str = "I'm a very^ we!rd* Str!ng.";
What I would like to do is removing all special characters from the above string and replace spaces and in case they are being typed, underscores, with a - character.
The above string would look like this after the "transformation":
var str = 'im-a-very-werd-strng';
replace(/[^a-z0-9\s]/gi, '') will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-') will replace underscores and spaces with hyphens:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')
Source for Regex: RegEx for Javascript to allow only alphanumeric
Here is a demo: http://jsfiddle.net/vNfrk/
Assuming by "special" you mean non-word characters, then that is pretty easy.
str = str.replace(/[_\W]+/g, "-")
str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')
Remove numbers, underscore, white-spaces and special characters from the string sentence.
str.replace(/[0-9`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');
Demo
this will remove all the special character
str.replace(/[_\W]+/g, "");
this is really helpful and solve my issue. Please run the below code and ensure it works
var str="hello world !#to&you%*()";
console.log(str.replace(/[_\W]+/g, ""));
Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');
The problem is that first code removes all the hyphens and then tries to replace them :)
You should reverse the replace calls and also add hyphen to second replace regex. Like this:
str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');
Remove/Replace all special chars in Jquery :
If
str = My name is "Ghanshyam" and from "java" background
and want to remove all special chars (") then use this
str=str.replace(/"/g,' ')
result:
My name is Ghanshyam and from java background
Where g means Global
var str = "I'm a very^ we!rd* Str!ng.";
$('body').html(str.replace(/[^a-z0-9\s]/gi, " ").replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace(/[_\s]/g, "-").toLowerCase());
First regex remove special characters with spaces than remove extra spaces from string and the last regex replace space with "-"

Categories