Please consider the following HTML <pre> element:
This is some
example code which
contains tabs
I would like to replace all of the tab characters with four non-breaking space characters in HTML (i.e. ). I have tested the above pre element with JavaScript for the presence of tab characters as follows:
$('pre').ready(function() {
alert(/\t/.test($(this).text()));
});
But it is always returned false. Can anyone tell me the correct process by which to replace tab spaces from the source code to HTML NBSPs? The tabs have been added by Komodo Edit, and are visible when viewing the source.
You can do it like this:
$('pre').html(function() {
return this.innerHTML.replace(/\t/g, ' ');
});
That will loop through all pre elements on the page and call the function for each of them. jQuery's html function uses the return value of the function we give to replace the content of each element. We're using String#replace to replace all (note the g flag on the regexp) tab characters in the HTML string with four non-breaking spaces.
Live example
It removes line breaks, extra spaces and line breaks:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
Demo:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
$('#acceptString').click(function() {
var str = prompt('enter string','');
if(str)
removeNewlines(str)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Enter String' id='acceptString' />
Try this:
var tab = RegExp("\\t", "g");
document.getElementById("text").value =
document.getElementById("text").value.replace(tab,' ');
Related
I currently load a value from my database straight into a hidden textarea.
<textarea name="text" id="text" style="visibility:hidden">
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
</textarea>
From there I pick up the textarea's content and run it trough several replace arguments with a simple Javascript, like
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function parser() {
post_text=post_text.replace(/\r?\n/g, "<br>");
post_text=post_text.replace(/\[size=1\]/g, "<span style=\"font-size:80%\">");
post_text=post_text.replace(/\[url=(.+?)\](.+?)\[\/url\]/g, "$2 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text=post_text.replace(/\[url\](.+?)\[\/url\]/g, "$1 <img src=\"images/link.gif\" style=\"border:0px\">");
document.getElementById('vorschau').innerHTML = post_text;
}, false);
</script>
<div id="vorschau"></div>
to render it into HTML which is then parsed by the Browser, so I do all the formatting of the entries on the Frontend/client side.
However, the textarea may also contain such an UBB tag:
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
I currently just replace the textarea UBB elements like any other content
post_text=post_text.replace(/\[textarea\]/g, "<textarea id=\"codeblock\" style=\"width:100%;min-height:200px;\">");
post_text=post_text.replace(/\[\/textarea\]/g, "</textarea>");
The issue with this is that my other code
post_text=post_text.replace(/\r?\n/g, "<br>");
post_text=post_text.replace(/\</g, "<");
post_text=post_text.replace(/\>/g, ">");
Does not skip the content within the [textarea][/textarea] elements resulting in a textarea filled with this:
Content showing raw <b>HTML</b> or any other code<br>Including line breaks </a>
Above example
So how do I prevent to replace anything within [textarea][/textarea] (which can occur more than once in id="text")?
What you might do, is use a dynamic pattern that captures from [textarea] till [/textarea] in group 1, and use an alternation to match what you want to replace.
Then use a callback function for replace. Check if group 1 exists, and if it does return it unmodified. If it does not, we have a match outside of the text area.
An example of the pattern with the alternation and match for <
(\[textarea][^]*\[\/textarea])|<
(\[textarea][^]*\[\/textarea]) Capture group 1, match from [textarea] till [/textarea]
| Or
< Match literally
Regex demo
Note to double escape the backslash in the RegExp constructor.
(Assuming this is the right order of replacements:)
const replacer = (text, find, replace) => text.replace(
new RegExp(`(\\[textarea][^]*\\[\\/textarea])|${find}`, "g"),
(m, g1) => g1 ? g1 : replace
);
document.addEventListener('DOMContentLoaded', function parser() {
let post_text = document.getElementById('text').value;
post_text = post_text.replace(/\[size=1]/g, "<span style=\"font-size:80%\">");
post_text = post_text.replace(/\[url=(.+?)](.+?)\[\/url\]/g, "$2 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text = post_text.replace(/\[url](.+?)\[\/url]/g, "$1 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text = replacer(post_text, "\\r?\\n", "<br>");
post_text = replacer(post_text, "<", "<");
post_text = replacer(post_text, ">", ">");
post_text = post_text.replace(/\[textarea]/g, "<textarea id=\"codeblock\" style=\"width:100%;min-height:200px;\">");
post_text = post_text.replace(/\[\/textarea]/g, "</textarea>");
document.getElementById('vorschau').innerHTML = post_text;
}, false);
<textarea name="text" id="text" rows="10" cols="60">
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
< here and > here and
</textarea>
<div id="vorschau"></div>
I am using a third-party plugin for javascript called QueryBuilder.
The problem is there is no way to trim the input after saved so the data is being saved like
testName=' test '
this is my javascript code, which is removing all spaces which is not what I want, I am trying to remove just space in the single quotes before and after all the text. Pretty much like a trim but the trim is not working so I need a regex to replace method
get_condition_sql__str = $.trim(get_condition_sql.sql);
get_condition_sql__clean = get_condition_sql__str.replace(/\s/g, '')
console.log(get_condition_sql__clean);
jQuery('.exception_conditions__sql').val(get_condition_sql__clean);
Lookahead for exactly one ' before the end of the string:
const input = `testName=' test '`;
const cleaned = input.replace(/ +(?=[^']*'$)/g, '');
console.log(cleaned);
There's only one word in the input, but if you need to preserve spaces between words inside the quotes, alternate between matching a ' on either side of spaces instead:
const input = `testName=' test test2 '`;
const cleaned = input.replace(/' +| +'/g, "'");
console.log(cleaned);
Please use this one for left space remove:
<script type="text/javascript">
var original_str3 = " This is a string"
//Strips all space to the left of the string
alert( original_str3.trimLeft() + ' <--- Without any spaces on the left' );
</script>
Or use this one for right space remove:
<script type="text/javascript">
var original_str4 = "This is a string "
//Strips all space to the right of the string
alert( original_str4.trimRight() + ' <--- Without any spaces on the right' );
For Remove space from both side character or string:
<script type="text/javascript">
var original_str2 = "S t r in g"
//Strips excessive white spaces i.e. retains only one space between each letter
var white_space_stripped_str = original_str2.replace(/\s+/g, ' ');
alert(white_space_stripped_str + ' <---- With exactly one space between each letter in case each letter has multiple spaces');
</script>
If any other are required then please let me know.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">"vSourceCountry = 'TEST'"</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = `testName=' test test2 '`;
var res = str .replace(/' +| +'/g, "'");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Result:
Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:
testName='test test2'
Or You can use etc as per required:
https://www.w3schools.com/jsref/jsref_replace.asp
This question already has answers here:
Matching quote wrapped strings in javascript with regex
(3 answers)
Closed 2 years ago.
I have a question, how can add <span style="color: blue"> to text in quotes.
Example:
.. and he said "Hello, I am Nick"
Using regex I want to achieve this result:
.. and he said <span style="color: blue>"Hello, I am Nick"</span>
I want to know how I can do that with regular expressions. Goal is to apply color only to text inside the quotes.
Using .replaceWith() function you can add span tag between any text with quotes.
$(document).ready(function() {
$("h2"). // all p tags
contents(). // select the actual contents of the tags
filter(function(i,el){ return el.nodeType === 3; }). // only the text nodes
each(function(i, el){
var $el = $(el); // take the text node as a jQuery element
var replaced = $el.text().replace(/"(.*?)"/g,'<span class="smallcaps">"$1"</span>') // wrap
$el.replaceWith(replaced); // and replace
});
});
.smallcaps {
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>and he said "Hello, i am Nick" and "I am good"</h2>
Use String.prototype.replace() method:
var str = document.querySelector('div').textContent;
var reg = /(".*\")+/g
var s = str.replace(reg, function(m){
return '<span style="color:blue">'+m+'</span>';
})
document.querySelector('div').innerHTML = s;
<div>and he said "Hello, I am Nick", some extra</div>
You can use the String's .replace() function as follows:
(1) If you want to keep the quotes and have them inside the <span>:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"[^"]*"/g, '<span style="color:blue">$&</span>');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
Notes:
The [^"] sequence in the regular expression defines a set of characters that matches all characters other than a double quote. Therefore, [^"]* matches zero or more characters that are not a double quote.
The $& in the replacement string will be replaced with the matched characters.
(2) If you do not want to keep the quotes:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"([^"]*)"/g, '<span style="color:blue">$1</span>');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
The parentheses in the regular expression create a capturing group. (Notice that the quotes are not within the capturing group.)
The $1 in the replacement string will be replaced with the first capturing group.
(3) If you want to keep the quotes, but have them outside the <span>:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"([^"]*)"/g, '"<span style="color:blue">$1</span>"');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
Note: This is the same as #2, but the quotes are included in the substitution string, so they are put back in the result string.
If regex is not mandatory, then try this split-map-join as well
var text = document.getElementById( "el" ).innerHTML;
function transform(input)
{
return input.split("\"").map( function(item,index){ if( index % 2 != 0 ){ item = '<span style="color: blue">' + item; } return item }).join("");
}
document.getElementById( "el" ).innerHTML = transform(text)
<div id="el">
and he said "Hello, i am Nick"
</div>
'and he said "Hello, I am Nick"'.replace(/"Hello, I am Nick"/, '<span style="color: blue">$&</span>');
How could I go about replacing a string:
Hello my name is <a href='/max'>max</a>!
<script>alert("DANGEROUS SCRIPT INJECTION");</script>
with
Hello my name is <a href='/max'>max</a>!
<script>alert("DANGEROUS SCRIPT INJECTION");</script>
I can easily have all the <,> replaced with <,> with:
string = string.replace(/</g, "<").replace(/>/g, ">");
but I still want to be able to have <a> links.
I have also looked into preventing script injection with:
var html = $(string.bold());
html.find('script').remove();
But I want to be able to still read the script tags rather than them being removed.
One approach to this problem is to use a regular expression with a strict look-behind pattern that only allows anchors that follow a certain format very closely.
Let's say you want to only allow links that exactly follow this example:
text
and
text
Build a regular expression that matches only "<" characters that are not followed by this valid pattern (negative lookbehind):
<(?!a href="https?:\/\/\w[\w.-\/\?#]+">\w+<\/a>)
One problem with this regular expression is that if you match it against your entire string, the < will still match the closing a element (</a>), so if you replace every match with a < you will break the anchor after all.
You can allow all closing </a> tags by appending an alternative to the negative look-behind:
<(?!a href="https?:\/\/\w[\w.-\/\?#]+">\w+<\/a>|\/a>)
Perhaps someone else has a better solution for that sub-problem.
Here is the final string.replace:
string.replace(/<(?!a href="https?:\/\/\w[\w.-\/\?#]+">\w+<\/a>|\/a>)/g, '<');
Note: All these input checks must always be done on the server side, on the client side the check can simply be circumvented and you'll have malicious data sent to your server despite the check.
This code snippet should do the trick. You can add additional tag names you wish to let pass as HTML tags in the array allowedTagNames.
// input
var html = "Hello my name is <a href='/max'>max</a>! <script>alert('DANGEROUS SCRIPT INJECTION');</script>";
var allowedTagNames = ["a"];
// output
var processedHTML = "";
var processingStart = 0;
// this block finds the next tag and processes it
while (true) {
var tagStart = html.indexOf("<", processingStart);
if (tagStart === -1) { break; }
var tagEnd = html.indexOf(">", tagStart);
if (tagEnd === -1) { break; }
var tagNameStart = tagStart + 1;
if (html[tagNameStart] === "/") {
// for closing tags
++tagNameStart;
}
// we expect there to be either a whitespace or a > after the tagName
var tagNameEnd = html.indexOf(" ", tagNameStart);
if (tagNameEnd === -1 || tagNameEnd > tagEnd) {
tagNameEnd = tagEnd;
}
var tagName = html.slice(tagNameStart, tagNameEnd);
// copy in text which is between this tag and the end of last tag
processedHTML += html.slice(processingStart, tagStart);
if (allowedTagNames.indexOf(tagName) === -1) {
processedHTML += "<" + html.slice(tagStart + 1, tagEnd) + ">";
} else {
processedHTML += html.slice(tagStart, tagEnd + 1);
}
processingStart = tagEnd + 1;
}
// copy the rest of input which wasn't processed
processedHTML += html.slice(processingStart);
NOTE: it won't work if there's a < or > inside a property of a tag.
For example: <a href=">">
You can use capture groups and lookarounds in Regex to achieve this
string = string.replace(/<((?!a )[^>]*)>/g, "<$1>").replace(/<\/a>/g, "</a>");
The first part replaces all the HTML tags (except anchor start tags <a>) from <tag> to <tag> and the second part replaces all the altered anchor end tags(</a>) from </a> back to </a>
If you want to replace only the <script... tags, the following code will do the trick ( you can run it in browser console ) and all other tags will not be changed. In my sample I added an extra line just to demonstrate how it works with multiple <script... tags inside.
let s = "Hello my name is <a href='/max'>max</a>!<script>alert(\"DANGEROUS SCRIPT INJECTION\");</script>";
s += "Hello my name is <a href='/bob'>bob</a>!<script>alert(\"DANGEROUS SCRIPT INJECTION\");</script>";
s.match(/<script.*?<\/script>/g).forEach(scr => s = s.replace(scr, scr.replace(/</g, "<").replace(/>/g, ">")));
console.log(s);
// OUTPUT: Hello my name is <a href='/max'>max</a>!<script>alert("DANGEROUS SCRIPT INJECTION");</script>Hello my name is <a href='/bob'>bob</a>!<script>alert("DANGEROUS SCRIPT INJECTION");</script>
Contenteditable div
var1 = 'x';
var2 = someVar
Target
<span class="frag">var1 = 'x'</span>;
<span class="frag">var2 = someVar</span>;
JS
$('#board_code_dup').children().each(function (index, child) {
var text = $(child).html();
//HOW TO DO THIS RIGHT?
text = text.replace(/([A-Za-z0-9_]+\s*=\s*[A-Za-z0-9&'"]+)/g, '<span class="frag">$1</span>');
});
How would i use HTML entities " ' here instead of ' " so that i can properly wrap it?
This is what I've tried "$('#board_code_dup').text()" and split it on "\n" instead ..
It will convert entities behind the scene like quotes or double quotes in the source. This might match in reg-exp.
var result = $('#board_code_dup').text().split("\n").map(function (el, idx){
return el.replace(/\s*;\s*$/,'').replace( /(\w+\s*=\s*[\w&"']+)/g,'<span class="frag">$1</span>');
});
alert(result.join(''));
Js fiddle Here
I hope this will help ..