Find the string occurence and wrap it with a span - javascript

<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div>cout<<"hey";cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
I wanted to find cout using regex, something like /cout[^;]*;/ and then wrap it with a span.
<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div><span id="group">cout<<"hey";</span>cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
How will i find the regex occurence and the wrap it with a span? Anyone please?
UPDATE: I inserted cin>>x; after cout, cin shouldn't be wrapped.
I want to use something like this
text.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>');
But i dont know how to apply it in DOM. anyone?
BUG for cin>> and cout<<, they cant be wrap until ; http://jsfiddle.net/3N4AE/11/

This is how you would apply the regex to your DOM using jQuery:
$('#wrapper div').filter(':contains("cout")').each(function () {
$(this).html($(this).text().replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
Demo fiddle

update Regex way
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.html(txt.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
DEMO
var x =$('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('').append('<span id="group">'+txt+'</span>');
updated after OP updated question
DEMO
var x = $('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
update
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
});
updated after koala-dev comment
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else if ($.trim(val) != '') {
x.append(val + ';');
}
});
});

This should help
var pattern = /cout[^;]*;/;
var txt = $('#wrapper').find('div:nth-child(2)').text();
var el = $('#wrapper').find('div:nth-child(2)');
$(el).text("").append('<span id="group">' + txt + '</span');
jsfiddle

Related

regex if else statement failing

here's a function that checks if there's a link in text (if so, replaces it with a clickable one)
example:
The actual resolution of this image is 3067x2276, not 4381x3251. See this page for information on how to find out what the resolution of an image is.
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
if (matches.length > 2) {
var replace = `${matches[1]}`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} else {
$("#text").append('<p>hello</p>');
}
});
}
<body>
<div class="container">
<div id="art" class="img column1">
</div>
<div id="text" class="comment column2">
</div>
</div>
</body>
I tried running it on chrome's javascript console, replacing $("#text").append... with console.log("hello"), and it works. Why does it not work on jsfiddle?
use try and catch instead
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
try {
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
var replace = `${matches[1]}`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} catch(err) {
$("#text").append('<p>' + rawComment + '</p>');
}
});
}
exec returns null if regex not matched result. Just check it at first.
...
if (matches && matches.length > 2) {
...

find and replace everything before character jquery

I have to display client information on site side for that I'm displaying email and other information as well.
Here I have to replace all the characters before # with * like
test#gmail.com
This is the example mail id I want result as
****#gmail.com
I tried below one only # is replacing with *
$('.element span').each(function() {
console.log($(this).text());
var text = $(this).text().replace('#', '*');
$(this).text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
<span>test#gmail.com</span>
</div>
How can I achieve this?
Thanks in advance.
Possible solution.
$('.element span').each(function() {
$(this).text($(this).text().replace(/.+(?=#)/g, '*'.repeat($(this).text().replace(/#.+/g, '').length)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
<span>test#gmail.com</span>
</div>
<div class="element">
<span>somethingelse#gmail.com</span>
</div>
Another possible solution, without regex:
document.querySelectorAll('p').forEach(function(el){
var text = el.innerText;
var substr = text.substr(0, text.lastIndexOf('#'));
el.innerText = text.replace(substr, '*'.repeat(substr.length));
});
<p>testa#gmail.com</p>
<p>testb#gmail.com</p>
<p>testc#anymail.com</p>
<p>testwithmoreasterisks#gmail.com</p>
Try to change your jQuery script to following script:
$(function(){
$('.element span').each(function() {
var index = $(this).text().indexOf("#");
var substring = $(this).text().substr(0, index);
var otherpart = $(this).text().substr(index);
for (var i = 0, len = substring.length; i < len; i++) {
substring = substring.replace(substring[i], '*');
}
console.log(substring + otherpart);
$(this).text(substring + otherpart);
});
});
Let me know if it is works.
try below code.
`<!DOCTYPE html>
<head>
</head>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="element">
<span>vinay.mbkumar#gmail.com</span>
</div>
<script>
function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}
$('.element span').each(function() {
var str = $(this).text();
console.log(str);
console.log(str.length)
var i = 0;
var ind = 0;
var text = "";
var repchar = "";
while (i < str.length) {
console.log(str.charAt(i));
if(str.charAt(i) == '#')
{
ind = i;
break;
}
i++;
}
console.log(ind);
for (i = 0; i < ind; i++)
{
repchar += "*";
}
text = replaceRange(str, 0, i , repchar);
console.log(text);
$(this).text(text);
});
</script>
</body>
</html>`
This is also a solution
var strArray = ("test#gmail.com").split("#");
var str = strArray[0].replace(/./gi, '*');
str =str +"#"+ strArray[1];

Highlight only matching text within a string (JQuery/Javascript)

I'm trying to highlight only matching text within a string at any point.
I have an input box which filters the results. Originally this worked fine to highlight the FIRST character, but the remit has changed to highlight the text within a string at any position.
Fiddle: Highlight matching text
It filters perfectly as it should, but highlights letters starting at the front, not the matching ones. I tried to use indexOf valThis to sort it out but I was probably doing it wrong.
Any help or pointers would be really appreciated.
$('#box').keyup(function () {
var valThis = this.value.toLowerCase();
var length = this.value.length;
$('.objType').each(function () {
var text = $(this).text(),
textL = text.toLowerCase(),
//n = textL.indexOf(valThis);
var htmlR = '<b>' + text.substr(0, length) + '</b>' + text.substr(length);
if(textL.includes(valThis))
{
$(this).html(htmlR).show()
}
else
{
$(this).hide();
}
});
});
The line
var htmlR = '<b>' + text.substr(0, length) + '</b>' + text.substr(length);
says "take length characters from the beginning of the string." You want to start with the first matching character, so you need to know where that is. So you want String#indexOf, not String#includes.
You also want to save the original text so you can compare against that, not against the text updated by the previous filter operation:
// Grab the original text
$(".objType").each(function() { // ***
$(this).data("original", $(this).text()); // ***
}) // ***
$('#box').keyup(function() {
var valThis = this.value.toLowerCase();
var length = this.value.length;
$('.objType').each(function() {
var text = $(this).data("original"), // ***
textL = text.toLowerCase(),
index = textL.indexOf(valThis); // ***
if (index !== -1) {
var htmlR = text.substr(0, index) + '<b>' + text.substr(index, length) + '</b>' + text.substr(index + length); // ***
$(this).html(htmlR).show()
} else {
$(this).hide();
}
});
});
Updated Fiddle, snippet:
// Grab the original text
$(".objType").each(function() { // ***
$(this).data("original", $(this).text()); // ***
}) // ***
$('#box').keyup(function() {
var valThis = this.value.toLowerCase();
var length = this.value.length;
$('.objType').each(function() {
var text = $(this).data("original"), // ***
textL = text.toLowerCase(),
index = textL.indexOf(valThis); // ***
if (index !== -1) {
var htmlR = text.substr(0, index) + '<b>' + text.substr(index, length) + '</b>' + text.substr(index + length); // ***
$(this).html(htmlR).show()
} else {
$(this).hide();
}
});
});
input[type="text"] {
width: 50%;
font-size: 110%;
margin: 10px;
padding: 5px;
float: left;
clear: left;
}
span {
float: left;
clear: left;
margin: 10px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="Filter results" id="box" type="text" />
<span class="objType" id="item1">Accepted Event Relation</span>
<span class="objType" id="item2">Case Status Value</span>
<span class="objType" id="item3">External Data Source</span>
<span class="objType" id="item4">Navigation Link Set</span>
Try this.
It does non-destructive copying
$('#box').keyup(function () {
var valThis = this.value.toLowerCase(),
length = this.value.length;
$('.objType').each(function () {
var text = $(this).text(),
textL = text.toLowerCase(),
textStart = textL.indexOf(valThis),
textEnd = textStart+valThis.length;
//n = textL.indexOf(valThis);
var htmlR = text.substring(0,textStart)+'<b>' + text.substring(textStart,textEnd) + '</b>' + text.substring(textStart+length);
if(textStart!=-1) {
$("#"+this.id+"r").html(htmlR).show()
$(this).hide();
}
else {
$("#"+this.id+"r").empty();
$(this).hide();
}
});
});
input[type="text"] {
width: 50%;
font-size: 110%;
margin:10px;
padding: 5px;
float:left;
clear:left;
}
span{
float:left;
clear:left;
margin:10px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="Filter results" id="box" type="text" />
<span class="objType" id="item1">Accepted Event Relation</span><span id="item1r"></span>
<span class="objType" id="item2">Case Status Value</span><span id="item2r"></span>
<span class="objType" id="item3">External Data Source</span><span id="item3r"></span>
<span class="objType" id="item4">Navigation Link Set</span><span id="item4r"></span>
I guess you need to use a combination of indexOf, RegEx and substring to find and highlight the position of the word in each string.
See Fiddle here:
https://jsfiddle.net/sxk7qj40/
$('#box').keyup(function () {
const valThis = this.value;
const length = this.value.length;
$('.objType').each(function () {
const text = $(this).text();
const textL = text.toLowerCase();
const position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
const matches = text.substring(position, (valThis.length + position));
const regex = new RegExp(matches, 'ig');
const highlighted = text.replace(regex, `<mark>${matches}</mark>`);
$(this).html(highlighted).show();
} else {
$(this).text(text);
$(this).hide();
}
});
});
You would not want to hardcode your substring position at 0, as this will always begin at the start of the string regardless.
Instead, you need to use indexOf, which will return the starting position. You can then use that in the substring to find the starting point that you want to replace. Note that indexOf will return -1 if not found, hence the if statement.
Where to end though? Well, this will come in as a combination of the start position we already have + the string length you just typed.
NOTE: For my own convenience, I used some es2015 features like const and template literals, but you can't use es2015, simply run it through Babel,
or manually replace these parts with var and string concatenation
respectively.
Hope this makes sense?
e.g. ES5 safe:
$('#box').keyup(function () {
var valThis = this.value;
var length = this.value.length;
$('.objType').each(function () {
var text = $(this).text();
var textL = text.toLowerCase();
var position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
var matches = text.substring(position, (valThis.length + position));
var regex = new RegExp(matches, 'ig');
var highlighted = text.replace(regex, '<mark>' + matches + '</mark>');
$(this).html(highlighted).show();
} else {
$(this).text(text);
$(this).hide();
}
});
});

How to add an "exception" or "condition" in this code (javascript, jquery)?

I would like to add an exception or condition in this code.
var a = 0;
$(document).ready(function() {
$(document).on("change", "#txtInput" ,function(){
$("#contenido").append("<tr><td>"+$("#txtInput").val()+"</td></tr>");
a += 1;
var str = 'Total Bianuales: '
$('p').html(str + a);
}
)
});
This is how it works: I get a value with the ID txtInput. I got some condition about this ID up in my code but I want to apply it when it add the value in a table that it's created. How do I make a condition that only append the value I get from txtInput when it's major or equal than 9?
Thanks for your help anyway!
Remember that change fires when input looses focus so you will need to click out of the control to cause it to fire. If you wanted it to fire on each keystroke then you want the input event.
var a = 0;
$(document).on("change", "#txtInput",function(){
var inputLength = this.value.length;
if (inputLength <= 8) { return; }
$("#contenido").append("<tr><td>" + this.value + "</td></tr>");
$("p").html('Total Bianuales: ' + (++a));
});
<input id="txtInput" />
<table id="contenido"></table>
<p></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var a = 0;
$(document).ready(function() {
$(document).on("change", "#txtInput" ,function(){
var textinput = parseInt($(this).val());
if (textinput > 8) {
$("#contenido").append("<tr><td>"+$(this).val()+"</td></tr>");
a += 1;
var str = 'Total Bianuales: '
$('p').html(str + a);
}}
);
});

javascript array to string conversion

I have this array in javascript:
[div.parts, div.editor, div.inside-1, div.container-2, div.inside-wrapper, div#content, div.whitebgpan, div, div#maindiv, body, html]
How can I convert it into string, so that the output will be:
div.parts div.editor div.inside-1 div.container-2 div.inside-wrapper div#content div.whitebgpan div div#maindiv body html
here is my code:
jQuery(document).on('click', function(e){
var ClickedParents = jQuery(e.target).parents(); //Get all parents of clicked element
var ClickedParents_array = jQuery.makeArray(ClickedParents); //Make array
console.log(ClickedParents_array); //Show output in colsole
});
You can use a combination of the jQuery each function and JavaScript's Array.Join function to solve this problem.
DEMO: http://jsfiddle.net/zay015ex/1/
I've artificially retrieved an array of jQuery objects to show how you can solve this, but the concept is common to your problem.
HTML
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
JavaScript
var arrayOfObjects = $('#parent').children();
var ids = [];
$.each(arrayOfObjects, function(i, val)
{
ids.push(val.id);
});
var idString = ids.join(' ');
You can read up more on the jQuery each function here.
You can read up more on the JavaScript's Array.Join function
here.
===== Update =====
Ok, the following code is tested, just open a console and paste this. it selects all div tags and convert into selector string.
$.map($('div'),function toSelector(elem){
var jqObj = $(elem)
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
})
===================
Supposing they're jquery objects, you have to build the string manually.
For example, do something like following. (not tested)
function toSelector(jqObj){
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
}
array.map(toSelector)
I think below code is helpful for you.
<script type="text/javascript">
String.prototype.replaceAll = function ( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
try{
var arr = [];
arr.push('div.parts', 'div.editor', 'div.inside-1', 'div.container-2', 'div.inside-wrapper', 'div#content', 'div.whitebgpan', 'div', 'div#maindiv', 'body', 'html');
var stringData = arr.toString();
stringData = stringData.replaceAll(",", " ");
console.log(stringData);
}catch(e){
alert(e)
}
</script>

Categories

Resources