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>');
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
I am not able to replace multiple $ signs using JavaScript/jQuery ,
my JavaScript replace code are as per bellow,
var str = $('#amt').html().replace("/\$/g","₹");
alert(str);
but it does not replace all occurrence, Please help me to replace $ by ₹ symbol.
Your regex is correct, but when wrapped it in quotes, it is no longer a RegEx, it's a string.
.replace(/\$/g, "₹");
And the HTML is not replaced it is just creating a string variable, use
$('#amt').html(function (i, oldHtml) {
return oldHtml.replace(/\$/g, "₹");
});
$('#amt').html(function(i, oldHtml) {
return oldHtml.replace(/\$/g, "₹");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="amt">
<div>Books: $150.00</div>
<div>Food: $2050.00</div>
<div>Total: $2200.00</div>
</div>
I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here
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,' ');