I need to detect some random regular expressions, and then apply them a style to each one, something like:
Replace Match[0] with <span class='found'> Match[0]</span>
Replace Match[1] with <span class='found'> Match[1]</span>
Replace Match[n] with <span class='found'> Match[n]</span>
I tried this
.replace(randomregexp, "<span class='found'>$1</span>");
but instead of Match[0] showing, it shows $1.
my code:
$("#query, article").keyup(
function change() {
if (document.getElementById("query").value == "");
else {
texts = document.getElementById("query").value;
regexpr= new RegExp(texts,"g");
document.getElementsByTagName("article")[0].innerHTML = $("article").text().replace(regexpr, '<b class="found">$1</b>');
}
}
);
You need to use wrap function. Try something like this:
.wrap('<span class="found"></span>')
or you may access matched string by using $& like this:
.replace(randomregexp, "<span class='found'>$&</span>");
If you could post mode code it would be helpful, but try .wrap('<span class="found"></span>)
Make sure you wrap your match in ( and ). If there is no matched text it'll just show $1.
texts = '('+document.getElementById("query").value+')';
Then $1 should work for the matched substring...
'hello'.replace(/(\w+)/,"<span class='found'>$1</span>")
// Outputs: "<span class='found'>hello</span>"
Related
I have some HTML where I've dynamically printed a bunch of elements, some containing a specific data attribute. Because my templating language can't efficiently make use of regular expressions, I need to use JavaSript (or JQuery) to select the data values, build a string, then add that string as a class to that original element.
Example of HTML:
<div class="item" data-ses-cat="This Cool Thing (Yes)"></div>
Example of Desired HTML after JavaScript:
<div class="item this-cool-thing-yes" data-ses-cat="This Cool Thing (Yes)"></div>
I just need to add a class to all tags that contain data-ses-cat then get the value for that data attribute, run regex, then add that new string as a class.
I feel like it should be fairly simple, but I haven't touched a lot of JQuery in a while.
Thanks for any help!
Remove every character that is not alphanumeric or a space, then lowercase it, then split on space, and join on dash.
$('.item[data-ses-cat]').each(function(){
var newClass = $(this).data('ses-cat')
.replace( /[^a-zA-Z0-9 ]/g, '' )
.toLowerCase()
.split( ' ' )
.join( '-' );
this.classList.add( newClass );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item" data-ses-cat="This Cool Thing (Yes)">Test</div>
And from your comments, here is a version that uses arrow functions.
$('.item[data-ses-cat]').each((index, element)=>{
var newClass = $(element).data('ses-cat')
.replace( /[^a-zA-Z0-9 ]/g, '' )
.toLowerCase()
.split( ' ' )
.join( '-' );
element.classList.add( newClass );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item" data-ses-cat="This Cool Thing (Yes)">Test</div>
A vanilla JS version of the code would look something like this:
function processElement(element) {
const clazz =
element.dataset.sesCat.toLowerCase()
.replace(/\(\)/g, '') // Remove brackets.
.replace(/ /g, '-'); // Replace spaces with dashes.
element.classList.add(clazz);
}
const sesCatElements = document.querySelectorAll('[data-ses-cat]');
sesCatElements.forEach(processElement);
Of course, you can tweak your RegExp exactly how you want it.
Here is some info on how Dataset API works.
And this, is how you work with CSS class names.
I want to replace spaces between html tags with nbsps using pure JavaScript.
This is my html:
<div><span>Apple</span> <span>Grapes</span></div>
You can see spaces between 2 span nodes. These spaces should be replaced by  s.
Result should be:
<div><span>Apple</span><span> </span><span>Grapes</span></div>
Please help me.
Try this simple logic
var input= "<div><span>Apple</span> <span>Grapes</span></div>"
var output = input.replace( /<\/span>\s*<span>/g, function(match){ return match.replace(/\s/g, " ") } );
console.log( output );
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>');
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 a HTML string ( not DOM element ) like :
<p>This is a sample dataa<p>
<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>
I need to append a <span class="spellerror"></span> to the words that have problem and that too only the Textual contents need to be checked and appended .
<p>This is a sample dataa<p>
<img src="Randomz" alt="Randomz Image"><span class="spellerror"> Randomz </span> is the name of the image</img>
My problem is that this is a mix of HTML and regex . Is it possible:
To make this some kind of a DOM element and then work on it ?
Or is there a regex way to achieve this.
I dont want to touch the attributes and if I modify Text contents , how do I publish it back ...because I need some HTML inserted there .
I dont love this solution, but it works:
'<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>'
.match(/<[^>]+>|[^<]+|<\/[^>]+>/g)
.map(function (text, index) {
if (index === 1) {
return text.replace(/(Randomz)/, '<span class="spellerror">$1</span>');
} else {
return text;
}
})
.join('');
The regex splits into opening tag, innerText, closing tag.
Then iterates on all members, if its the innerText, it replaces with desired text
Then joins.
Im stil trying to think of something less round-about but thats all i got
Use some form of templating:
String.prototype.template = String.prototype.template ||
function (){
var args = Array.prototype.slice.call(arguments)
,str = this
;
function replacer(a){
var aa = Number(a.substr(1))-1;
return args[aa];
}
return str.replace(/(\$\d+)/gm,replacer);
};
var thestring = [ '<p>This is a sample dataa</p><img src="Randomz"'
,' alt="Randomz Image">$1Randomz$2 '
,'is the name of the image</img>'].join('')
,nwString = theString.template('<span class="spellerror">','</span>');