I want to select all literal letter s but not literal word \s
(?<!\\)s
works in c# but I'm not able to adjust it to work with javascript. how do I disallow literal \s in javascript matching all literal s?
for example int the expression: test\ss should match test\ss
Edit:
as Mitch says I want to catch all literal s that are not after a literal \
You can create DIY Boundaries ...
var r = 'test\\ss'.replace(/(^|[^\\])s/gi, '$1ş');
console.log(r); //=> 'teşt\sş'
Or use a workaround:
var r = 'test\\ss'.replace(/(\\)?s/gi, function($0,$1) { return $1 ? $0 : 'ş'; });
According to your comment in your question, try this then
/(?:\B|\s)s/g
Try this in your browsers console to confirm it works
re = /(?:\B|\s)s/g;
str = 'test\\ss';
res = str.match(re)
console.log(str.replace(re, '0'));
res will have 2 results in it
Related
I want to find ++ or -- or // or ** sign in in string can anyone help me?
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = ++,--,//,**;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
This finds doubles of the characters by a backreference:
/([+\/*-])\1/g
[from q. comments]: i know this but when i type var patt1 = /[++]/i; code find + and ++
[++] means one arbitrary of the characters. Normally + is the qantifier "1 or more" and needs to be escaped by a leading backslash when it should be a literal, except in brackets where it does not have any special meaning.
Characters that do need to be escaped in character classes are e.g. the escape character itself (backslash), the expression delimimiter (slash), the closing bracket and the range operator (dash/minus), the latter except at the end of the character class as in my code example.
A character class [] matches one character. A quantifier, e.g. [abc]{2} would match "aa", "bb", but "ab" as well.
You can use a backreference to a match in parentheses:
/(abc)\1
Here the \1 refers to the first parentheses (abc). The entire expression would match "abcabc".
To clarify again: We could use a quantifier on the backreference:
/([+\/*-])\1{9}/g
This matches exactly 10 equal characters out of the class, the subpattern itself and 9 backreferences more.
/.../g finds all occurrences due to the modifier global (g).
test-case on regextester.com
Define your pattern like this:
var patt1 = /\+\+|--|\/\/|\*\*/;
Now it should do what you want.
More info about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
You can use:
/\+\+|--|\/\/|\*\*/
as your expression.
Here I have escaped the special characters by using a backslash before each (\).
I've also used .test(str) on the regular expression as all you need is a boolean (true/false) result.
See working example below:
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = patt1.test(res);
if (result) {
alert("you cant do this :l");
document.getElementById('screen').innerHTML = '';
}
<div id="screen">
This is some++ text
</div>
Try this:-
As
n+:- Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
We need to use backslash before this special characters.
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
<div id="screen">2121++</div>
I didn't find a solution inside regex's documentation for my current problem. I'm using javascript, html.
My code is like this:
var text = 'This [close](animal) is a dog';
I want to get this using regex:
'This {animal} is a dog';
what I mean, i want to have 'close' replaced with { and }.
I know, there's a solution like:
var res = text.replace('[close](','{').replace(')','}');
but in my case, I have many rules and I don't want to duplicate that line to do so. Sometimes I'm using other replacement like '[ xxxxx ]'.
Any idea? Thank you!
You may use
var text = 'This [close](animal) is a dog';
console.log(text.replace(/\[[^\][]*]\(([^()]*)\)/g, '{$1}'));
See the regex demo.
Details
\[ - a [ char
[^\][]* - 0 or more chars other than [ and ]
]\( - a ]( substring
([^()]*) - Capturing group 1: any 0 or more chars other than ( and )
\) - a ) char.
The {$1} replacement is the contents of the capturing group enclosed with braces.
If you can only have two values - close and open - inside [...], and replace close with {...} and open with }...{, you may use
var text = '[open](animal)This [close](animal) is a dog';
console.log(text.replace(/\[(open|close)]\(([^()]*)\)/g, function($0, $1, $2) {
return $1==='close' ? '{'+$2+'}' : '}'+$2+'{';})
);
Don't forget, that you can pass custom regex in Array.prototype.replace. In your case it would be text.replace(/[close](/g,'{'). Full solution of your question will look like:
var res = res.replace(/\[\w+\]\((.*)\)/, (a, b) => {
console.log(a, b);
return `{${b}}`;
});
The brackets around .* used to 'capture' animal inside variable b
Thank you Wiktor, I'v found a solution by what you said
var res0 = text.replace(/\[close]\(([^()]*)\)/g, '{$1}');
var res1 = text.replace(/\[open]\(([^()]*)\)/g, '}$1{');
Sorry if i did miskates, i'm not used to english expression so :-)
I'm trying to validate a form using regular expressions, the conditions are:
It has to be a numeric value
It CAN have up to three decimal places(0,1,2 are allowed too)
It has to be divided by a comma(,)
I already got it to work using HTML5-Patterns with this:
pattern='\d+(,\d{1,3})?'
Since patterns are not supported by IE9, I tried doing it with js:
var numPattern = /\d+(,\d{1,3})?/;
if(!numPattern.test(menge.val()))
{
checkvalidate = false;
}
Where did I go wrong?
Examples
valid: 1,234 ; 2,00 ; 5 ; 0,1
invalid: 1,2345 ; 2.00 ; 56a
You'll need to start your regex with ^ and end it with $ to make sure the entire input string/line is matched.
/^\d+(,\d{1,3})?$/
Here's a "demo" in which all your examples are valid/invalid:
https://regex101.com/r/oP5yJ4/1
(Using regex101.com to debug your regular expression patterns is often very useful)
Note that: (without ^ and $)
var pattern_without = /\d+(,\d{1,3})?/;
pattern_without.test("56a") === true; // matches, but only "56"
pattern_without.test("1,2345") === true; // matches, but only "1,234"
but: (with ^ and $)
var pattern_with = /^\d+(,\d{1,3})?$/;
pattern_with.test("56a") === false; // no match
pattern_with.test("1,2345") === false; // no match
You can use this regex:
/^\d+(?:,\d{1,3})*$/
RegEx Demo
Try this expression:
\d+(,\d{3})*([.]\d{1,3})?
Valid examples:
1,200.123
1,200.12
1,200.1
1.123
1,200,222
1,200,002
You can use the RegExp object.
var str = "123545,123";
var patt = new RegExp("/^(?:\d*\,\d{1,3}|\d+)$/");
var res = patt.test(str);
After execution, res will be true, since str matches the pattern you're looking for,
I'm wondering how to remove the first and last character of a string in Javascript.
My url is showing /installers/ and I just want installers.
Sometimes it will be /installers/services/ and I just need installers/services.
So I can't just simply strip the slashes /.
Here you go
var yourString = "/installers/";
var result = yourString.substring(1, yourString.length-1);
console.log(result);
Or you can use .slice as suggested by Ankit Gupta
var yourString = "/installers/services/";
var result = yourString.slice(1,-1);
console.log(result);
Documentation for the slice and substring.
It may be nicer one to use slice like :
string.slice(1, -1)
I don't think jQuery has anything to do with this. Anyway, try the following :
url = url.replace(/^\/|\/$/g, '');
If you dont always have a starting or trailing slash, you could regex it. While regexes are slower then simple replaces/slices, it has a bit more room for logic:
"/installers/services/".replace(/^\/?|\/?$/g, "")
# /installers/services/ -> installers/services
# /installers/services -> installers/services
# installers/services/ -> installers/services
The regex explained:
['start with' ^] + [Optional?] + [slash]: ^/?, escaped -> ^\/?
The pipe ( | ) can be read as or
['ends with' $] + [Optional ?] + [slash] -> /?$, escaped -> \/?$
Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash.
Technically it isn't "optional", but "zero or one times".
You can do something like that :
"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')
This regex is a common way to have the same behaviour of the trim function used in many languages.
A possible implementation of trim function is :
function trim(string, char){
if(!char) char = ' '; //space by default
char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
var regex_1 = new RegExp("^" + char + "+", "g");
var regex_2 = new RegExp(char + "+$", "g");
return string.replace(regex_1, '').replace(regex_2, '');
}
Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///
You can also simply do :
"/installers/".substring(1, string.length-1);
You can use substring method
s = s.substring(0, s.length - 1) //removes last character
another alternative is slice method
if you need to remove the first leter of string
string.slice(1, 0)
and for remove last letter
string.slice(0, -1)
use .replace(/.*\/(\S+)\//img,"$1")
"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
It is too nicer shortcode.
response.data.slice(1,-1) // "Prince"
-> Prince
url=url.substring(1,url.Length-1);
This way you can use the directories if it is like .../.../.../... etc.
We would like to split a string on instances of the pipe character |, but not if that character is preceded by an escape character, e.g. \|.
ex we would like to see the following string split into the following components
1|2|3\|4|5
1
2
3\|4
5
I'm expecting to be able to use the following javascript function, split, which takes a regular expression. What regex would I pass to split? We are cross platform and would like to support current and previous versions (1 version back) of IE, FF, and Chrome if possible.
Instead of a split, do a global match (the same way a lexical analyzer would):
match anything other than \\ or |
or match any escaped char
Something like this:
var str = "1|2|3\\|4|5";
var matches = str.match(/([^\\|]|\\.)+/g);
A quick explanation: ([^\\|]|\\.) matches either any character except '\' and '|' (pattern: [^\\|]) or (pattern: |) it matches any escaped character (pattern: \\.). The + after it tells it to match the previous once or more: the pattern ([^\\|]|\\.) will therefor be matches once or more. The g at the end of the regex literal tells the JavaScript regex engine to match the pattern globally instead of matching it just once.
What you're looking for is a "negative look-behind matching regular expression".
This isn't pretty, but it should split the list for you:
var output = input.replace(/(\\)?|/g, function($0,$1){ return $1?$1:$0+'\n';});
This will take your input string and replace all of the '|' characters NOT immediately preceded by a '\' character and replace them with '\n' characters.
A regex solution was posted as I was looking into this. So I just went ahead and wrote one without it. I did some simple benchmarks and it is -slightly- faster (I expected it to be slower...).
Without using Regex, if I understood what you desire, this should do the job:
function doSplit(input) {
var output = [];
var currPos = 0,
prevPos = -1;
while ((currPos = input.indexOf('|', currPos + 1)) != -1) {
if (input[currPos-1] == "\\") continue;
var recollect = input.substr(prevPos + 1, currPos - prevPos - 1);
prevPos = currPos;
output.push(recollect);
}
var recollect = input.substr(prevPos + 1);
output.push(recollect);
return output;
}
doSplit('1|2|3\\|4|5'); //returns [ '1', '2', '3\\|4', '5' ]