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

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.

Related

How to replace multiple characters from text?

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

Javascript Regex remove specialchars except - and æøå

I got this:
var stringToReplace = 'æøasdasd\89-asdasd sse';
var desired = stringToReplace.replace(/[^\w\s]/gi, '');
alert(desired);
I found the replace rule from another SO question.
This works fine, it gives output:
asdasd89asdasd sse
Although I would like to set up additional rules:
Keep æøå characters
Keep - character
Turn whitespace/space into a - character
So the output would be:
æøåasdasd89-asdasd-sse
I know I can run an extra line:
stringtoReplace.replace(' ', '-');
to accomplish my 3) goal - but I dont know what to do with the 1 and 2), since I am not into regex expressions ?
This should work:
str = str.replace(/[^æøå\w -]+/g, '').replace(/ +/g, '-');
Live Demo: http://ideone.com/d60qrX
You can just add the special characters to the exclusion list.
/[^\w\sæøå-]/gi
Fiddle with example here.
And as you said - you can use another replace to replace spaces with dashes
Your original regex [^\w\s] targets any character which isn't a word or whitespace character (-, for example). To include other characters in this regex's 'whitelist', simply add them to that character group:
stringToReplace.replace(/[^\w\sæøå-]/gi, '');
As for replacing spaces with hyphens, you cannot do both in a single regex. You can, however, use a string replacement afterwards to solve that.
stringToReplace.replace(" ","-");

Javascript Regex I'm struggling with

I am admittedly NOT a regex person but usually I can figure my way around something. This one has me stumped...
I need to match and replace a double greater than str (>>) that has an optional leading space. I know this doesn't work but something along the lines of...
/\s\s+[>>]/
But that's obviously no good.
Would appreciate any help. This site has been an amazing resource for me over the years and I can't believe I'm only getting around to posting something now, so it goes to show even a knucklehead like me has been able to benefit without bothering people... until now:) Thanks in advance.
For >> both inside a string and with leading whitespace, try:
/(\s*)(>>){1}/
If you want the space to be optional, then you can simply do this :
/>>/
And you may use it as a replacement pattern with the g modifier :
str = str.replace(/>>/g, 'something')
If you want to check that a string is >> with maybe some space before, then use
/^\s?>>$/
Breaking down your example:
\s will match any white-space character
\s+ will match one or more white-space characters
[>>] will match one > (see more below on this)
So your expression will match a > preceeded by at least two white-space characters.
If you want to match zero-or-more you will have to use *; fex \s*.
Square brackets are used to denote sets of characters, and will match any of the characters in the set; fex [abc] will match a, b or c, but only one character at time.
Single characters in a regular expression will match that character; fex > will match one greater-than sign.
Putting it together we get the following regular expression for your case:
/\s*>>/
This should work with the optional space.
/\s{0,}>>/g
Visit this link to test the matches.
If you want it to match an unlimited amount of leading space characters:
/ *>>/
If you want it to match 0 or 1 leading space character:
/ ?>>/
use this :
str.replace(/\s+>>/g, 'whatever');
This regex should work.
/\s*[>]{2}/
This is cleaner
/\s*>>/
Tested:
var pattern = /\s*>>/;
s1 = " >>";
s2 = ">>";
s3 = ">> surrounding text";
s4 = "surrounding >> text";
s5 = "surrounding>>text";
s1.match(pattern);
[" >>"]
s2.match(pattern);
[">>"]
s3.match(pattern);
[">>"]
s4.match(pattern);
[" >>"]
s5.match(pattern);
[">>"]
Replacement example
var pattern = /\s*>>/;
var s6 = " >> surrounding text";
s6.replace(pattern, ">");
"> surrounding text"

Do word boundaries work on symbol characters?

I'm trying to implement word boundaries in my emoticons feature for a chat. But for some reason I can't seem to get the word boundaries to work. I am new to regex.
So when I do:
var reg = /\b\Hi\b/gi;
var str = 'HiHiHi Hi HiHiHi Hi';
alert(str.replace(reg, ''));
This happens: Jsfiddle
It actually works fine, and does remove those 2 Hi's that are standing alone.
But when I change the reg to an escaped smiley and then change the string:
var reg = /\b\:\)\b/gi;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(reg, ''));
This happens:
Jsfiddle
It just doesn't work. The string stays the same. Is it that word boundaries can't be used on symbols? If so, how does Facebook do it on their chats?
Word boundaries \b represent a zero-width boundary between word characters \w (in javascript, [A-Za-z_]) and non-word characters \W (everything else).
Because of this, there will not be a boundary between two emoticons or when the emoticon is surrounded by spaces, punctuation, etc.
The simplest regex would be /[:;]-?[()]/gi, which supports smileys ) and frownies ( with optional dashes and eyes : or winks ;.
Edit:
This will require either a space or the beginning of the string (as a capturing group since Javascript doesn't support look-behinds), then it uses the above regex, then it must be followed by the end of string or whitespace.
var reg = /(\s|^)[:;]-?[()](?:\s|$)/gi;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(reg, '$1'));
Should replace in these situations: :-), cool :( not!
Should not replace in these situations: Digits:(0,1,2,3), hi :(.
As \b will not work in this case, you could use:
var re = /(\s|^):\)(?!\S)/g;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(re, '$1'));
Which works like a space boundary.
You can add several smileys to it like so:
/(\s|^)(?::\)|:\(|:\||:\]|:\[)(?!\S)/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