jQuery remove special characters from string and more - javascript

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

Related

Can't replace "[" and "]" characters in a string in Javascript

I'm trying to replace "[" and "]" characters in the string using javascript.
when I'm doing
newString = oldString.replace("[]", "");
then it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.
But when I'm doing:
newString = oldString.replace(/[]/g, "");
or
newString = oldString.replace(/([])/g, "");
nothing is happens. I've also tried with HTML numbers like
newString = oldString.replace(/[]/g, "");
but it doesn't work neither. Any ideas how to make it?
You either need to escape the opening square bracket, and add a pipe between them:
newString = oldString.replace(/\[|]/g, "");
Or you need to add them in a character class (square brackets) and escape them both:
newString = oldString.replace(/[\[\]]/g, "");
DEMO
"...there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {... If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash."
[] in a regex is a character class. Since you haven't escaped, them you're saying a "find any of the following characters", and not providing any. Try /[\[\]]/ instead.
edit: #andy is right. forgot to put in a container [].
This is a simple solution :
newString = oldString.split("[]").join("");
had a similair situation. i just used backslash like so.
-replace '\[','' -replace ']',''

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(" ","-");

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.

Regex to capture characters between the last white space character and the end of string

I'm trying to determine the characters between the last white space characer and the end of the string.
Example
Input: "this and that"
Output: "that"
I have tried the regex below but it doesnt work!
var regex = /[\s]$/
Can do without regex
var result = string.substring(string.lastIndexOf(" ")+1);
Using regex
result = string.match(/\s[a-z]+$/i)[0].trim();
I suggest you to use simple regex pattern
\S+$
Javascript test code:
document.writeln("this and that".match(/\S+$/));
Output:
that
Test it here.
You could just remove everything up to the last space.
s.replace(/.* /, '')
Or, to match any white space...
s.replace(/.*\s/, '')
Your example matches just one space character at the end of the string. Use
/\s\S+$/
to match any number.

replace empty space with dash only if trailing string

I'm using regEx and replace method to replace an empty space with a dash but I only want this to happen if there is a following character. For example
if the input field looked like this then replace empty space between temp and string with dash
input = "temp string";
if it looked like this then it would just remove the empty space
input = "temp ";
here is my regEx replace right now. But not sure how to check if there are trailing characters.
input.value.replace(/\s+/g, '-');
DEMO
input = $.trim(input.replace(/\b \b/g, '-'));
\b (word boundaries) info
jQuery.trim() api
This should do the trick:
the first replace takes care of the trailing spaces (if there's at least one)
the second one performs your original replacement
str.replace(/\s+$/g,'').replace(/\s+/g, '-');
DEMO
/\s+$/ only finds trailing spaces, so add .replace(/\s+$/, '') after .value

Categories