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
Related
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.
So I'm trying to parse a string similar to the way StackOverflow's tags work. So letters and numbers are allowed, but everything else should be stripped. Also spaces should be replaced with hyphens, but only if they are inside the word and not have disallowed characters before them.
This is what I have right now:
label = label.trim();
label = label.toLowerCase();
label = label.replace(/[^A-Za-z0-9\s]/g,'');
label = label.replace(/ /g, '-');
This works but with a few caveats, for example this:
/ this. is-a %&&66 test tag . <-- (4 spaces here, the arrow and this text is not part of the test string)
Becomes:
-this-is-a66-test-tag----
Expected:
this-is-a66-test-tag
I looked at this to get what I have now:
How to remove everything but letters, numbers, space, exclamation and question mark from string?
But like I said it doesn't fully give me what I'm looking for.
How do I tweak my code to give me what I want?
You need to make 2 changes:
Since you do not replace all whitespace with the first replace you need to replace all whitespace chars with the second regex (so, a plain space must be replaced with \s, and even better, with \s+ to replace multiple consecutive occurrences),
To get rid of leading/trailing hyphens in the end, use trim() after the first replace.
So, the actual fix will look like
var label = " / this. is-a %&&66 test tag . ";
label = label.replace(/[^a-z0-9\s-]/ig,'')
.trim()
.replace(/\s+/g, '-')
.toLowerCase();
console.log(label); // => this-isa-66-test-tag
Note that if you add - to the first regex, /[^a-z0-9\s-]/ig, you will also keep the original hyphens in the output and it will look like this-is-a-66-test-tag for the current test case.
Use trim just before changing all spaces with hyphens.
You can use this function:
function tagit(label) {
label = label.toLowerCase().replace(/[^A-Za-z0-9\s]/g,'');
return label.trim().replace(/ /g, '-'); }
var str = 'this. is-a %&&66 test tag .'
console.log(tagit(str));
//=> "this-isa-66-test-tag"
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.
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 "-"
I want to remove space in the beggining of each line.
I have data in each line with a set of spaces in the beginning so data appears in the middle, I want to remove spaces in the beginning of each line.
tmp = tmp.replace(/(<([^>]+)>)/g,"")
How can I add the ^\s condition into that replace()?
To remove all leading spaces:
str = str.replace(/^ +/gm, '');
The regex is quite simple - one or more spaces at the start. The more interesting bits are the flags - /g (global) to replace all matches and not just the first, and /m (multiline) so that the caret matches the beginning of each line, and not just the beginning of the string.
Working example: http://jsbin.com/oyeci4
var text = " this is a string \n"+
" \t with a much of new lines \n";
text.replace(/^\s*/gm, '');
this supports multiple spaces of different types including tabs.
If all you need is to remove one space, then this regex is all you need:
^\s
So in JavaScript:
yourString.replace(/(?<=\n) /gm,"");