Replacing commas in resultset with new line in jQuery - javascript

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.

Related

Regex to get the text between two characters?

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

Javascript regex to match more than one line break

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.

Manipulate Javascript RegExp occurrences in string

I'm converting phone numbers into a clickable url. I have an html string with random phone numbers appearing in a non particular/consistent way:
Fidel Velazquez (834)316-90-90 ↵Libertad (834) 316-2930 ↵
I'm using regex in order to search the occurrences and "linkify" them, this is the function that helps with that:
var regex = new RegExp(
"\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+",
"g"
);
return inputText.replace(regex, '$&');
The problem is, that for the example above, I'm getting a white space before the phone number, and that is preventing the html link from working correctly (i.e I'm getting " (834)316-90-90" instead of "(834)316-90-90").
Is there something I can change directly on my regex? Or is there a way to apply a .replace(' ', ''); only to the occurrences?
Thanks!
You can use a function for replacement, allowing you to customise the replacement string.
var inputText = `Fidel Velazquez (834)316-90-90
Libertad (834) 316-2930
`;
var regex = new RegExp(
"\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+",
"g"
);
var output = inputText.replace(regex, function(m) {
var match = m.replace(/ /g, '');
return `${m}`;
});
console.log(output);
Or you can construct a more careful regular expression, taking the original apart, and putting it together in a different way, using capture groups. This is more restricted, but sufficient for what you described. (Also, new RegExp is not idiomatic, you'd only use it when you have dynamically generated regular expression.)
For your specific trouble, you could even require the space to be matched only when the previous thing matches... Many different solutions, depending exactly what your requirement is. Note that this regular expression will also match some things that do not look like phone numbers:

Finding image url via using Regex

Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

How to allow whitespace in Regex

I have a regex which allows only to enter integers and floats in a text box.
Regex Code:-
("^[0-9]*(?:[.][0-9]*|)$");
But it gives an error when the user enters whitespace at the beginning and end of the entered values. I want the user to allow spaces at the beginning and at the end as optional, so I changed the regex as below but it didn't work.
Note: Spaces may be spaces or tabs.
Test Case: User might enter:
"10","10.23"," 10","10 "," 10.23","10.23 "
Any number of spaces are allowed.
("^(?:\s)*[0-9]*(?:[.][0-9]*|)$")
I am newbie with regex, so any help will be highly appreciated.
Thank you.
Try this:
/^\s*[0-9]*(?:[.][0-9]*|)\s*$/;
You don't have to wrap a single entity in a group to repeat it, and I have added a second zero-or-more-spaces at the end which is what you are missing to make it work.
Note: You have not posted the code you use to create the RegExp object, but if it is new RegExp(string), remember to escape your backslashes (by doubling them):
var r = new RegExp("^\\s*[0-9]*(?:[.][0-9]*|)\\s*$");
Also, as #Blender suggests, this can be simplified to:
/^\s*[0-9]*(?:\.[0-9]*)?\s*$/;
Or, using \d instead of [0-9]:
/^\s*\d*(?:\.\d*)?\s*$/;
You don't necessarily need a Regular Expression: !isNaN(Number(textboxvalue.trim())) would be sufficient.
Otherwise, try /^\s{0,}\d+\.{0,1}\d+\s{0,}$/. Test:
var testvalues = ["10","10.23"," 10","10 "," 10.23","10.23 ","10.24.25"];
for (var i=0;i<testvalues.length;i+=1){
console.log(/^\s{0,}\d+\.{0,1}\d+\s{0,}$/.test(testvalues[i]));
}
//=> 6 x true, 1 x false

Categories