JavaScript regex to replace a specific word with a line break - javascript

I have a number of strings coming back from the database and I need to separate them into 2 lines based on a specific word that the backend person can insert in the string. (The word or symbol can be anything.)
I have tried the following:
var str = "some string some string space some string";
str = str.replace(/space/g, "\n")
console.log(str);
but the string still appears over one line only.
...
var str = "some string some stringspacesome string";
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
console.log(str);
var screenHeight = (this.state.windowHeight -90) + 'px';
return (
<div>
<Header />
<section className={"main " + this.state.color_name} style={{minHeight: screenHeight}}>
<div className="content-wrapper">
<div className="content" >
<h1>{str}</h1>
...
After the replacement, the str variable is going to be used as the contents of an h1 element.

If you want the string to be used as the contents of an HTML tag, then \n isn't the proper way to have it display on two lines. Rather, you'll need to use an html break tag of <br/>. You can either replace that into your strings, like this:
str = str.replace(/space/g, "<br/>")
Or for simplicity's sake, since you mentioned that the "space" string to replace can be anything, it seems like you could just skip the replacement altogether and use the desired replacement on the backend.

Related

Parse unicode in string using $.each

I'm trying to filter a string from a onmousemove event (tooltip).
The filtered string needs to be showed as text.
The problem is that the string looks like:
This string needs to be filtered. \r\n There is also unicode in this string \u00EB.
What I want:
This string needs to be filtered. There is also unicode in this string: ë
The HTML looks as follows:
<img onmousemove="showInfo(event,'This string needs to be filtered. \r\n There is also unicode in this string: \u00EB.');" onmouseout="hideInfo();" />
This is what I tried:
$(document).ready(function() {
$('td > img').each(function() {
var toolTip = $(this).attr('onmousemove'),
comment = toolTip.match(/([\'])(\\?.)*?\1/),
parentCell = $(this).parent();
$("div.timelineRow").css("padding", "7px");
$("<td><b>Info:</b><span> " + comment[0] + "</span></td>").insertAfter(parentCell);
$(this).insertAfter(parentCell);
});
});
Try decoding your Unicode character using JSON.parse. (Note the wrapping in double quotes to make it valid JSON).
Then replace the new lines with <br> tags to convert them into HTML line break elements (The browser won't render \r\n).
e.g.
var htmlComment = JSON.parse('"' + comment[0] + '"').replace("\r\n", "<br>");
$("<td><b>Info:</b><span> " + htmlComment + "</span></td>").insertAfter(parentCell);

How to escape html string having multiple double quotes

I have received the following string from my ajax request:
As per json doc, "quotes must be escaped "
This is stored in data.description and is embedded in the template as:
''
data-title's value is used as a caption for lightbox plugin pop up. I tried the following function:
var HtmlEncode = function(s) {
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
as:
''
Now since the data.description contains multiple quotes javascript assumes them as multiple argument and throws error. I searched many other Stackoverflow posts which suggest to append the data in a div and retrieve its inner HTML but that is possible in my case.
Thanks
Change only the quotes that are the same as those will be surrounding the data-title. Like this:
var description = data.description.replace(/"/g, "'");
var template = '';
You can replace the double quotes in your string with single quotes or any other symbol in order for it to work inside double quotes.
you can do this with String.replace(/["]+/g,"'") this will replace the double quotes in the string with a single quote, the g in the reg-ex tells it to use all the string.
you can also fake it by using 2 single quotes like this String.replace(/["]+/g,"''"), and it will fake double quotes for you.
var HtmlEncode = function(s) {
return s.replace(/["]+/g,"''");
}
Solution 1
Escape it with replace and a regexp:
var HtmlEncode = function(s) {
return s.replace(/"/g, '\\"').replace(/'/g, "\\'");
}
''
Solution 2
Let jQuery doing this for you (only if you are using it).
var tpl = $('');
tpl.data('title', data.description);
Try to replace the quotes with HTML entity equivalents after which you can then safely use it on attributes.
var desc = data.description.replace(/'/g, "'").replace(/"/g, """);
''
Here's a Fiddle to demonstrate the solution.

Removing newline character in javascript

I have a text in a textarea and get the value using the .val() attribute. I would like to remove the linebreaks (which is the doublespace)?
i tried using the .replace
sampleText = sampleText.replace(/(\r\n|\n|\r)/gm,"");
But it did not give me the correct solution.
sample text from my textarea
when i tried the .replace(), it will do like this
how do i remove the space between sample 2 and sample 3? it should look like this..
split by new line, filter out an empty line and finally join
sampleText = sampleText.split(/\n|\r/).filter(function(value){
return value.trim().length > 0;
}).join("\n");
Example
var sampleText = "Sample 1\nSample 2\n\nSample 3";
sampleText = sampleText.split("\n").filter(function(value){
return value.trim().length > 0;
}).join("\n");
document.write('<pre>'+sampleText+'</pre>');
You need to double up on your by using the + sign on your group filtering to only include the double occurences, and don't replace them with an empty string but with a new newline.
For more information about the plus sign I recommend to read http://www.regular-expressions.info/repeat.html
This way every double occurence will be replaced by a single occurence, which is what you want I guess
var sampleText = "Sample1\n\nSample2\n\r\n\r\r\r\nSample3";
document.write('<pre>Before:\n'+sampleText);
// The plus makes sure the matched pattern is repetitive and keeps replacing the doubles
sampleText = sampleText.replace(/(\r\n|\n|\r)+/gm,"\r\n");
document.write('\n\nAfter:\n'+sampleText+'</pre>');
You can do the replacement of two line breaks:
var sampleText = "Sample1\nSample2\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSample3";
sampleText = sampleText.replace(/(\n){2,}/gm, "\n"); // matches 2 linebreaks to infinity;
document.querySelector('pre').innerHTML = sampleText;
<pre></pre>
Or just with .join() while creating an array out of string with .split():
var sampleText = "Sample1\nSample2\n\n\n\n\n\n\n\n\n\nSample3".split(/\n{2,}/gm).join('\n')
document.querySelector('pre').innerHTML = sampleText;
<pre></pre>

Using js regex to replace simple markup styles like **bold** to <b>bold</b>

I'm trying to take a chunk of plain text and convert parts of it into html tags. I don't need a full rich editor, just these few tags:
**bold**
__underline__
~~italics~~
--strike--
<<http://www.link.com>>
This is the method I have attempted to write but my lack of regex/js seems to be holding it back:
function toMarkup($this) {
var text = $this.text();
text = text.replace("\*\*(.*)\*\*", "<b>$1</b>");
text = text.replace("__(.*)__", "<u>$1</u>");
text = text.replace("~~(.*)~~", "<i>$1</i>");
text = text.replace("--(.*)--", "<del>$1</del>");
text = text.replace("<<(.*)>>", "<a href='$1'>Link</a>");
$this.html(text);
}
Any glaring errors as to why these replaces are not working? Another issue I'm just now realizing is by converting this text to html I am unescaping any other potential tags that may be malicious. A bonus would be any advice on how to only escape these elements and nothing else.
First of all, they are just string, not regexs. Secondly you should use not-greedy .*.
Also, you may want to use the g modifier to match every occourrence in the text.
function toMarkup($this) {
var text = $this.text();
text = text.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
text = text.replace(/__(.*?)__/g, "<u>$1</u>");
text = text.replace(/~~(.*?)~~/g, "<i>$1</i>");
text = text.replace(/--(.*?)--/g, "<del>$1</del>");
text = text.replace(/<<(.*?)>>/g, "<a href='$1'>Link</a>");
$this.html(text);
}
Use a Regexp object as the first argument to text.replace() instead of a string:
function toMarkup($this) {
var text = $this.text();
text = text.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
text = text.replace(/__(.*?)__/g, "<u>$1</u>");
text = text.replace(/~~(.*?)~~/g, "<i>$1</i>");
text = text.replace(/--(.*?)--/g, "<del>$1</del>");
text = text.replace(/<<(.*?)>>/g, "<a href='$1'>Link</a>");
$this.html(text);
}
Note that I also replaced all of the .* with .*? which will match as few characters as possible, otherwise your matches may be too long. For example you would match from the first ** to the very last ** instead of stopping at the next one. The regex also needs the g flag so that all matches will be replaced (thanks Aaron).
function toMarkup($this) {
$this.html ($this.text ().replace (/(__|~~|--|\*\*)(.*?)\1|<<(.*?)>>\/g,
function (m, m1, m2, m3) {
m[1] = {'**' : 'b>', '__': 'u>', '--': 'del>', '~~': 'i>'}[m[1]];
return m[3] ? 'Link'
: ('<' + m[1] + m[2] + '</' + m[1]);
});
}
Note that you cannot nest these, i.e. if you say __--abc--__ will be converted to <u>--abc--</u>.

How can I replace newlines/line breaks with spaces in javascript?

I have a var that contains a big list of words (millions) in this format:
var words = "
car
house
home
computer
go
went
";
I want to make a function that will replace the newline between each word with space.
So the results would something look like this:
car house home computer go went
You can use the .replace() function:
words = words.replace(/\n/g, " ");
Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.
Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.
let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");
console.log("After:");
console.log(words);
In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use
var new_words = words.replace(/[\r\n]+/g," ");
See regex demo
To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:
[ - start of a positive character class matching any single char defined inside it:
\r - (\x0D) - \n] - a carriage return (CR)
\n - (\x0A) - a line feed character (LF)
\x0B - a line tabulation (LT)
\x0C - form feed (FF)
\u0085 - next line (NEL)
\u2028 - line separator (LS)
\u2029 - paragraph separator (PS)
] - end of the character class
+ - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
/g - find and replace all occurrences in the provided string.
var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Some simple solution would look like
words.replace(/(\n)/g," ");
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')
const words = `He had
concluded that pigs
must be able
to fly in Hog Heaven.
`
document.body.innerHTML = "<pre>without-Trim-And-Remove:\n" + words + "</pre>";
trimAndRemoveSymbols=(text)=>{
return text.replace(/[\n]+/g, '').trim();
}
document.body.innerHTML += "<pre>Trim-And-Remove:\n" + trimAndRemoveSymbols(words) + "</pre>";

Categories