Javascript textarea flatten string - javascript

var newString = someString.replace(/\n/, '#');
Works great, when i do an alert;
alert(newString);
It appears as this:
"Firstline
#Secondline
#ThirdLine"
I wish for it to display:
"Firstline#SecondLine#Thirdline"
This is screwing up my other coding!
Can anyone help?

Some OS have \r\n for newlines. So, add an optional carriage return character to the RegExp. Also, add a global flag to your RegExp if you want to replace all occurrences:
var newString = someString.replace(/\r?\n/g, '#');

Try using...
var newString = someString.replace(/\n\r?/g, '#'))

Try:
someString.replace(/[\r\n]+/, '#');

If you are trying to prepend # to each line you might want this:
someString.replace(/^/gm, "#")
#Firstline
#Secondline
#ThirdLine

I would recommmend the following
function flatString(s) {
// remove line separators (windows and linux) and trim multiple spaces
s = s.replace(/\r\n/g, ' ')
.replace(/\r/g, ' ')
.replace(/\n/g, ' ')
.replace(/[ ]+/g, ' ')
.trim();
return s;
}
You first delete the Windows line ends (\r\n are always together), then you remove the single characters (for linux line ends).
At this point, you flatted the string. However, depending on how many newline characters you had, you may end up with many spaces. So we try to convert all n-spaces to single spaces, and lastly do a trim so we get the shortest string as possible.
NOTE: this can be further optimized to try to run the most regex possibilities in a single execution, but it makes the cut at least.

Related

replace \r\n with < br /> as text

Trying for 2 hours to replace \r\n with < br/> but it seems to be impossible.
I don't know what i'm doing! Please help!
const text = '"Hello!\r\n\r\nThis is a dog!'
const checkText = str=> {
const match = /\r|\n/.exec(text);
if (match) {
//return str.replace(/(?:\\[rn]|[\r\n]+)+/g, '<br/>');
return str.replace('/r/n', '<br/>');
}
return str;
};
checkText(text)
Just do this:
text.replace(/\r\n/g, '<br/>');
Covering all the possible new line character combinations.
String tmp = s.replaceAll("\r\n", "<br>"); // Windows
tmp = tmp.replaceAll("\r", "<br>"); // Old MAC
return tmp.replaceAll("\n", "<br>"); // Linux / UNIX
You may try:
(text+ '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
There are multiple things wrong with your code:
String.prototype.replace only replaces the first occurrence of a string. You need to use a regex argument with the /g flag to replace all occurrences.
Escapes use a backslash, not a forward slash: Use \r\n, not /r/n.
checkText returns a string, but your call-site doesn't do anything with the returned string - it's just dropped. Strings are immutable in JavaScript.
I don't recommend using strings to hold HTML because it can (very easily) cause HTML-injection (including <script>-injection) attacks.
Instead, do one of the following:
Use String.prototype.split and HTML-encode each string in the array and join with "<br />".
Add the string directly to the document with .textContent (don't use innerText anymore) and give the parent element the CSS style whitespace: pre-wrap;.

Regular expression for removing whitespaces

I have some text which looks like this -
" tushar is a good boy "
Using javascript I want to remove all the extra white spaces in a string.
The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -
"tushar is a good boy"
I am using the following code at the moment-
str.replace(/(\s\s\s*)/g, ' ')
This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.
This can be done in a single String#replace call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}
trims leading whitespace
trims trailing whitespace
normalizes tabs, newlines, and multiple spaces to a single regular space
Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim add this.
Trim string in JavaScript?
Since everyone is complaining about .trim(), you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
JSFiddle
This regex may be useful to remove the whitespaces
/^\s+|\s+$/g
Try:
str.replace(/^\s+|\s+$/, '')
.replace(/\s+/, ' ');
try
var str = " tushar is a good boy ";
str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
first replace is delete leading and trailing spaces of a string.

extracting middle OR final part of a string

I want to extract only the first fontname out of a URL-string from the Google Webfont Directory. Here are some examples of possible strings and what part should be returned:
fonts.googleapis.com/css?family=Raleway // "Raleway"
fonts.googleapis.com/css?family=Caesar+Dressing // "Caesar Dressing"
fonts.googleapis.com/css?family=Raleway:300,400 // "Raleway"
fonts.googleapis.com/css?family=Raleway|Fondamento // "Raleway"
fonts.googleapis.com/css?family=Caesar+Dressing|Raleway:300,400|Fondamento // "Caesar Dressing"
So sometimes it's just one fontname, sometimes it has a weight indicated by a colon (:) and sometimes there are more fontnames divided by a pipe (|).
I have tried /family=(\S*)[:|]/ but it only matches the strings with :or |. I could do it like this, but it's not a nice solution:
var fontUrl = "fonts.googleapis.com/css?family=Caesar+Dressing|Raleway:300,400|Fondamento";
var fontName = /family=(\S*)/.exec(fontUrl)[1].replace(/\+/, " ");
if (fontName.indexOf(':') != -1){
fontName = fontName.split(':')[0];
}
if (fontName.indexOf('|') != -1){
fontName = fontName.split('|')[0];
}
console.log(fontName);
Is there a nice regex solution to this?
Instead of matching the character that (might) follow the string you want, match only the string you want except those characters:
/family=([^\s:|]*)/
Alternatively, you'd use a lookahead like this:
/family=(\S*?)(?=$|[:|])/
That should be better:
/family=([^:|]*)/
Of course for the + case, you'll have to replace it afterwards (or before maybe).
You can use (choose the i and m modifier in all case):
family=([a-z]+\+?[a-z]+)
or more simply
family=([a-z+]+)
or to avoid matching the + char:
family=([a-z]+)\+?([a-z]+)?
but it is an easyer way to use the second solution, and to replace the + chars with a space after.
try this:
/family\=(\S+?)[\:\|,]{0,2}\S*/ims
No regex is required in this case, unless you are good with regex's or test them thoroughly then you are likely to make mistakes.
var fontUrls = [];
fontUrls.push("fonts.googleapis.com/css?family=Raleway");
fontUrls.push("fonts.googleapis.com/css?family=Caesar+Dressing");
fontUrls.push("fonts.googleapis.com/css?family=Raleway:300,400");
fontUrls.push("fonts.googleapis.com/css?family=Raleway|Fondamento");
fontUrls.push("fonts.googleapis.com/css?family=Caesar+Dressing|Raleway:300,400|Fondamento");
function getFirstFont(url) {
return url.split("=")[1].split("|")[0].split(":")[0];
}
fontUrls.forEach(function (fontUrl) {
console.log(getFirstFont(fontUrl));
});
on jsfiddle

How to replace all the \ from a string with space in javascript?

For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"

Regex for matching spaces not preceded by commas

I need to convert a string like this:
tag, tag2, longer tag, tag3
to:
tag, tag2, longer-tag, tag3
To make this short, I need to replace spaces not preceded by commas with hyphens, and I need to do this in Javascript.
I think this should work
var re = new RegExp("([^,\s])\s+" "g");
var result = tagString.replace(re, "$1-");
Edit: Updated after Blixt's observation.
mystring.replace(/([^,])\s+/i "$1-"); There's a better way to do it, but I can't ever remember the syntax
[^,] = Not a comma
Edit Sorry, didn't notice the replace before. I've now updated my answer:
var exp = new RegExp("([^,]) ");
tags = tags.replace(exp, "$1-");
text.replace(/([^,]) /, '$1-');
Unfortunately, Javascript doesn't seem to support negative lookbehinds, so you have to use something like this (modified from here):
var output = 'tag, tag2, longer tag, tag3'.replace(/(,)?t/g, function($0, $1){
return $1 ? $0 : '-';
});
[^,] - The first character is not comma, the second character is space and it searches for that kind of string
([a-zA-Z] ){1,}
Maybe? Not tested. something like that.

Categories

Resources