I need a javascript regex that will not allow more than one line break or carriage return. One line break is OK, more than one should not be permitted. I have this which does not allow any, but I'm unable to modify it to allow only one line break?
^[^\n\r]*$
The round brackets constitute a group. Your group is "\n\r", which should not be multiple. So you use a "+", that constitute 1 or more. In following case it will replace every multiple "\n\r" with "\n\r\" and every single "\n\r" with it.
var multiple = "hello\n\r\n\rworld\n\r!"
var single = multiple.replace(/(\n\r)+/g, "\\n\\r");
console.log(single);
Instead of looking for ^[\n\r]* look for ^\n\r[\n\r]*
var regpat = /^(\n\r)[\n\r]*/;
var str = "\n\r\n\r";
str.replace(re, '$1');
You can use match to text for multiple \n and throw an alert, like so:
var text = "hello\nworld\n\nmore here\n"
if (text.match(/\n[\n]+/g)){
alert("Error mulitple new lines");
}
You may want to first remove the \r or alter the above to also match \r also.
Related
I want to replace a text after a forward slash and before a end parantheses excluding the characters.
My text:
<h3>notThisText/IWantToReplaceThis)<h3>
$('h3').text($('h3').text().replace(regEx, 'textReplaced'));
Wanted result after replace:
notThisText/textReplaced)
I have tried
regex = /([^\/]+$)+/ //replaces the parantheses as well
regex = \/([^\)]+) //replaces the slash as well
but as you can see in my comments neither of these excludes both the slash and the end parantheses. Can someone help?
A pattern like /(?<=\/)[^)]+(?=\))/ won't work in JS as its regex engine does not support a lookbehind construct. So, you should use one of the following solutions:
s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')
The (...) forms a capturing group that can be referenced to with $ + number, a backreference, from the replacement pattern. The first solution is consuming / and ), and puts them into capturing groups. If you need to match consecutive, overlapping matches, use the second solution (s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')). If the ) is not required at the end, the third solution (replace(/(\/)[^)]+/, '$1textReplaced')) will do. The last solution (s.replace(/\/[^)]+\)/, '/textReplaced)')) will work if the / and ) are static values known beforehand.
You can use str.split('/')
var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);
Try Following: In your case startChar='/', endChar = ')', origString=$('h3').text()
function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}
First of all, you didn't define clearly what is the format of the text which you want to replace and the non-replacement part. For example,
Does notThisText contain any slash /?
Does IWantToReplaceThis contain any parentheses )?
Since there are too many uncertainties, the answer here only shows up the pattern exactly matches your example:
yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`
I thought it was very simple to find out. But how many ways I tried still not work properly.
Below is the test snippet.
"100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)".replace(/[\.,\d]*/g, '{n}')
And I want the result like below.
{n}$ and {n}EUR {n}USD {n}$ ({n})
The * is your problem, change the regex to /[.,\d]+/g instead.
"100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)".replace(/[.,\d]+/g, '{n}');
Output
{n}$ and {n}EUR {n}USD {n}$ ({n})
JSFiddle Example Check console screen for the output.
The problem here is that [\.,\d]* can match an empty string. The first step would be to use [.,\d]+ so that at least one of these characters matches.
But a better regex would be \d[.,\d]* because it ensures the replaced characters begin with a digit, so it won't replace periods in sentences.
If you want to go further, you can also use (?=[.,\d]*\d)[.,\d]+ if to handle numbers starting with periods. This one would be the proper answer for your case. The lookahead ensures there's at least one digit anywhere in the replaced text.
Note that you don't need to escape the . inside a character class.
\.?\d[^\s]*\d
Try this.Replace with {n}.See demo.
http://regex101.com/r/kP8uF5/3
var re = /\.?\d[^\s]*\d/gm;
var str = '100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)';
var subst = '{n}';
var result = str.replace(re, subst);
Can someone please tell me WHY my simple expression doesn't capture the optional arbitrary length .suffix fragments following hello, matching complete lines?
Instead, it matches the ENTIRE LINE (hello.aa.b goodbye) instead of the contents of the capture parenthesis.
Using this code (see JSFIDDLE):
//var line = "hello goodbye"; // desired: suffix null
//var line = "hello.aa goodbye"; // desired: suffix[0]=.aa
var line = "hello.aa.b goodbye"; // desired: suffix[0]=.aa suffix[1]=.b
var suffix = line.match(/^hello(\.[^\.]*)*\sgoodbye$/g);
I've been working on this simple expression for OVER three hours and I'm beginning to believe I have a fundamental misunderstanding of how capturing works: isn't there a "cursor" gobbling up each line character-by-character and capturing content inside the parenthesis ()?
I originally started from Perl and then PHP. When I started with JavaScript, I got stuck with this situation once myself.
In JavaScript, the GLOBAL match does NOT produce a multidimensional array. In other words, in GLOBAL match there is only match[0] (no sub-patterns).
Please note that suffix[0] matches the whole string.
Try this:
//var line = "hello goodbye"; // desired: suffix undefined
//var line = "hello.aa goodbye"; // desired: suffix[1]=.aa
var line = "hello.aa.b goodbye"; // desired: suffix[1]=.aa suffix[2]=.b
var suffix = line.match(/^hello(\.[^.]+)?(\.[^.]+)?\s+goodbye$/);
If you have to use a global match, then you have to capture the whole strings first, then run a second RegEx to get the sub-patterns.
Good luck
:)
Update: Further Explanation
If each string only has ONE matchable pattern (like var line = "hello.aa.b goodbye";)
then you can use the pattern I posted above (without the GLOBAL modifier)
If a sting has more than ONE matchable pattern, then look at the following:
// modifier g means it will match more than once in the string
// ^ at the start mean starting with, when you wan the match to start form the beginning of the string
// $ means the end of the string
// if you have ^.....$ it means the whole string should be a ONE match
var suffix = line.match(/^hello(\.[^.]+)?(\.[^.]+)?\s+goodbye$/g);
var line = 'hello.aa goodbye and more hello.aa.b goodbye and some more hello.cc.dd goodbye';
// no match here since the whole of the string doesn't match the RegEx
var suffix = line.match(/^hello(\.[^.]+)?(\.[^.]+)?\s+goodbye$/);
// one match here, only the first one since it is not a GLOBAL match (hello.aa goodbye)
// suffix[0] = hello.aa goodbye
// suffix[1] = .aa
// suffix[2] = undefined
var suffix = line.match(/hello(\.[^.]+)?(\.[^.]+)?\s+goodbye/);
// 3 matches here (but no sub-patterns), only a one dimensional array with GLOBAL match in JavaScript
// suffix[0] = hello.aa goodbye
// suffix[1] = hello.aa.b goodbye
// suffix[2] = hello.cc.dd goodbye
var suffix = line.match(/hello(\.[^.]+)?(\.[^.]+)?\s+goodbye/g);
I hope that helps.
:)
inside ()
please do not look for . and then some space , instead look for . and some characters and finally outside () look for that space
A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations.
var suffix = line.match(/^hello((\.[^\.]*)*)\sgoodbye$/g);
if (suffix !== null)
suffix = suffix[1].match(/(\.[^\.\s]*)/g)
and I recommand regex101 site.
Using the global flag with the match method doesn't return any capturing groups. See the specification.
Although you use ()* it's only one capturing group. The * only defines that the content has to be matched 0 or more time before the space comes.
As #EveryEvery has pointed out you can use a two-step approach.
I have not had to do something like this in the past and am wondering if it is indeed possible. I am allowing multiple code numbers to be added in an so long as they are delimited by commas. What I am wanting to do is upon the user clicking on the "okay" button that a showing the numbers entered will show them one on top of each other with a "delete" button next to them. That part is easy...the hard part is getting the comma stripped out and the new line placed in its stead.
Are there any examples or samples that anyone can point me too?
You'd use String#replace with a regular expression using the g flag ("global") for the "search" part, and a replacement string of your choosing (from your question, I'm not sure whether you want <br> — e.g., an HTML line break — or \n which really is a newline [but remember newlines are treated like spaces in HTML]). E.g.:
var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/,/g, '<br>'); // Or \n, depending on your needs
Or if you want to allow for spaces, you'd put optional spaces either side of the comma in the regex:
var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/ *, */g, '<br>'); // Or \n, depending on your needs
To replace all occurrences of a string you need to use a regexp with the g (global) modifier:
var numlist = "1,4,6,7,3,34,34,634,34";
var numlistNewLine = numlist.replace(/,/g, '\n');
Alternatively, use .split() and .join()
var newList = numList.split(',').join('\n');
var numlist = "1,4,6,7,3,34,34,634,34";
var numlistNewLine = numlist.replace(',','\n');
No jQuery needed. String has a nice replace() function for you.
I have a string and I need to fix it in order to append it to a query.
Say I have the string "A Basket For Every Occasion" and I want it to be "A-Basket-For-Every-Occasion"
I need to find a space and replace it with a hyphen. Then, I need to check if there is another space in the string. If not, return the fixed string. If so, run the same process again.
Sounds like a recursive function to me but I am not sure how to set it up. Any help would be greatly appreciated.
You can use a regex replacement like this:
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
The "g" flag in the regex will cause all spaces to get replaced.
You may want to collapse multiple spaces to a single hyphen so you don't end up with multiple dashes in a row. That would look like this:
var str = "A Basket For Every Occasion";
str = str.replace(/\s+/g, "-");
Use replace and find for whitespaces \s globally (flag g)
var a = "asd asd sad".replace(/\s/g,"-");
a becomes
"asd-asd-sad"
Try
value = value.split(' ').join('-');
I used this to get rid of my spaces. Instead of the hyphen I made it empty and works great. Also it is all JS. .split(limiter) will delete the limiter and puts the string pieces in an array (with no limiter elements) then you can join the array with the hyphens.