Im pretty new to regex and am trying to remove a leading underscore '_' from any string.
replace(/^[_]+/, "")
This works, but I want to be sure: Is this the correct way to do it?
As I can't find a lot about this special problem around the web, I'm asking about it here.
This should be enough:
replace(/^_/, '');
That works however, it will remove 1-n number of leading underscores. For example, _x becomes x but __x becomes x as well; all the way to n number of leading underscores. If you only want to remove the first leading underscore use the following:
some_string.replace(/^_{1}/, '');
This is using a quantifier to match only 1. Note that this quantifier is not greedy, + quantifier is one or more and greedy. You could also use your original code with the non-greedy modifier ? as follows:
some_string.replace(/^[_]+?/, '');
One last note, you don't need to use the character class operator, [...], in this case. It's not wrong or bad form, just unnecessary.
Related
This is my string:
<address>tel+1234567890</address>
This is my regex:
([\d].*<)
which matches this:
1234567890<
but I dont want to match the last <character.
You can use a positive lookahead:
\d+(?=<)
The (?=...) syntax makes sure what's inside the parens matches at that position, without moving the match cursor forward, thus without consuming the input string. It's also called a zero-width assertion.
By the way, the square brackets in [\d] are redundant, so you can omit them. Also, I've changed the regex, but perhaps you really meant to match this:
\d.*?(?=<)
This pattern matches everything between a digit and a <, including the digit. It makes use of an ungreedy quantifier (*?) to match up until the first < if there are several.
([\d]+)
This should work , try it out and let me know
Check the demo
Also as #LucasTrzesniewski said , you can use the look ahead
(\d+.(?=<))
Here is the demo
I've got three working regexp's,
string.replace(\catalogue\g, "") // replace a the word catalogue
string.replace(/[/:]/g, "") // replace the characters /, :
string.replace(\20%\g, "") // replace '20%'
Instead of replacing the string three times, I want to combine my regexp's.
Wanted result = 'removethewordnow';
var string = 'rem:ove20%the/word:catalogue20%now';
My latest try was:
string.replace(/\catalogue\b|[/20%:]/g, ""); // works, but catalouge is unaffected and 20% isn't combined as a word
Off the top of my head:
string.replace(/(catalogue|[\/:]|20%)/g,"");
Just use an alternative, i.e. separate each of the regular expressions you had before by the alternation operator |:
catalogue|20%|[/:]
Also note that you cannot just combine character classes and literal strings in the way you have done there. Above naïve combination works and everything beyond that might be optimisation (even if it can't be optimised further in this case) – but that only works if you don't change the language described by the regex.
You seem to be having a typo there (\c), also you don't want 20% inside the character class (and you should escape the slash). You also need to remove the word boundaries if you want to allow catalogue20% to match - there is no boundary between catalogue and 20, therefore the \b fails:
string.replace(/catalogue|20%|[\/:]/g, "");
var string = 'rem:ove20%the/word:catalogue20%now';
string.replace(/([:/]|20%|catalogue)/g, '');
\b refers to a word boundary, but your word catalogue is mixed with other words. So your regex should be:
string.replace(/catalogue|[\/20%:]/g, "");
Also do escape the / with \/.
string.replace(/catalogue|20%|[/:]/g, '')
I would like to replace all the characters other than 0-9 in a string, using Javascript.
Why would this regex not work ?
"a100.dfwe".replace(/([^0-9])+/i, "")
You need the /g modifier to replace every occurrence:
"a100.dfwe".replace(/[^0-9]+/g, "");
I also removed the redundant i modifier and the unused capturing sub-expression braces for you. As others have pointed out, you can also use \D to shorten it even further:
"a100.dfwe".replace(/\D+/g, "");
\D means “not digit”:
"a100.dfwe".replace(/\D/g, "")
What about negative numbers:
Using Andy E's example works unless you have a negative number. Then it removes the '-' symbol also leaving you with an always positive number (which might be ok). However if you want to keep number less than 0 I would suggest the following:
"a-100.dfwe".replace(/(?!-)[^0-9.]/g, "") //equals -100
But be careful, because this will leave all '-' symbols, giving you an error if your text looks like "-a-100.dfwe"
It doesn't work because the character class [^0-9] (= anything but digits) with the repetition modifier + will only match one sequence of non-numeric characters, such as "aaa".
For your purpose, use the /g modifier as the others suggest (to replace all matches globally), and you could also use the pre-defined character class \D (= not a digit) instead of [^0-9], which would result in the more concise regex /\D+/.
"string#! 134".replace(/[^a-z^0-9]+/g, " ");
this would return "string 134"
Based off of #user3324764's answer - Make a prototype function and convert the number to a number.
String.prototype.extractNumber = function ()
{
return Number(this.replace(/(?!-)[^0-9.]/g, ""));
};
Example:
"123.456px".extractNumber(); // 123.456
I need to match all occurrences of // in a string in a Javascript regex
It can't match /// or /
So far I have (.*[^\/])\/{2}([^\/].*)
which is basically "something that isn't /, followed by // followed by something that isn't /"
The approach seems to work apart from when the string I want to match starts with //
This doesn't work:
//example
This does
stuff // example
How do I solve this problem?
Edit: A bit more context - I am trying to replace // with !, so I am then using:
result = result.replace(myRegex, "$1 ! $2");
Replace two slashes that either begin the string or do not follow a slash,
and are followed by anything not a slash or the end of the string.
s=s.replace(/(^|[^/])\/{2}([^/]|$)/g,'$1!$2');
It looks like it wouldn't work for example// either.
The problem is because you're matching // preceded and followed by at least one non-slash character. This can be solved by anchoring the regex, and then you can make the preceding/following text optional:
^(.*[^\/])?\/{2}([^\/].*)?$
Use negative lookahead/lookbehind assertions:
(.*)(?<!/)//(?!/)(.*)
Use this:
/([^/]*)(\/{2})([^/]*)/g
e.g.
alert("///exam//ple".replace(/([^/]*)(\/{2})([^/]*)/g, "$1$3"));
EDIT: Updated the expression as per the comment.
/[/]{2}/
e.g:
alert("//example".replace(/[/]{2}/, ""));
This does not answer the OP's question about using regex, but since some of the original comments suggested using .replaceAll, since not everyone who reads the question in the future wants to use regex, since people might mistakenly assume that regex is the only alternative, and since these details cannot be accommodated by submitting a comment, here's a poor man's non-regex approach:
Temporarily replace the three contiguous characters with something that would never naturally occur — really important when dealing with user-entered values.
Replace the remaining two contiguous characters using .replaceAll().
Return the original three contiguous characters.
For instance, let's say you wanted to remove all instances of ".." without affecting occurrences of "...".
var cleansedText = $(this).text().toString()
.replaceAll("...", "☰☸☧")
.replaceAll("..", "")
.replaceAll("☰☸☧", "...")
;
$(this).text(cleansedText);
Perhaps not as fast as regex for longer strings, but works great for short ones.
I have everything in place to create slugs from titles, but there is one issue. My RegEx replaces spaces with hyphens. But when a user types "Hi there" (multiple spaces) the slug ends up as "Hi-----there". When really it should be "Hi-there".
Should I create the regular expression so that it only replaces a space when there is a character either side?
Or is there an easier way to do this?
I use this:
yourslug.replace(/\W+/g, '-')
This replaces all occurrences of one or more non-alphanumeric characters with a single dash.
Just match multiple whitespace characters.
s/\s+/-/g
Daniel's answer is correct.
However if somebody is looking for complete solution I like this function,
http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/
Thanks to "dense13"!
It might be the easiest to fold repeated -s into one - as the last step:
replace /-{2,}/ by "-"
Or if you only want this to affect spaces, fold spaces instead (before the other steps, obviously)
I would replace [\s]+ with '-' and then replace [^\w-] with ''
You may want to trim the string first, to avoid leading and trailing hyphens.
function hyphenSpace(s){
s= (s.trim)? s.trim(): s.replace(/^\s+|\s+$/g,'');
return s.split(/\s+/).join('-');
}