I'm having a small problem with a regexp pattern. I don't have regexp knowledge, so I couldn't solve it.
I have this text:
var text = "this (is) some (ran)dom text";
and I want to capture anything between (). So after following this tutorial I came up with this pattern:
var re = /(\(\w*\))/g;
which works fine. But what I want to do now is replace the found matches, or rather modify. I want to wrap the found matches with a span tag. So I used this code:
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
text.replace(re, spanOpen + text.match(re) + spanClose);
even though the code works, I don't get the result I want. It outputs:
as HTML
this <span style="color: silver;">(is),(ran)</span> some <span style="color: silver;">(is),(ran)</span>dom text
as text
this (is),(ran) some (is),(ran)dom text
You can check the example in fiddle. How can I fix this?
The code in fiddle:
var text = "this (is) some (ran)dom text";
var re = /(\(\w*\))/g;
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
var original = "original: " + text + "<br>";
var desired = "desired: this " +spanOpen+"(is)"+spanClose+ " some " +spanOpen+"(ran)"+spanClose+ "dom text<br>";
var output = "output: " + text.replace(re, spanOpen + text.match(re) + spanClose);
var result = original + desired + output;
document.body.innerHTML = result;
If the title is wrong or misleading, I'll change it.
The .replace() method can take a function as the 2nd parameter. That will come in handy here.
var output = "output: " + text.replace(re, function(match){
return spanOpen + match + spanClose
});
The function will be called for each individual match.
You can also use '$&' in your replace string to reference each match
var output = "output: " + text.replace(re, spanOpen + '$&' + spanClose);
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
text.match(re) is returning an array of the result, so what you can do is loop this array and replace your string with each items, like this:
var matches = text.match(re);
var output = "output: " + text;
for (var i = 0; i < matches.length; i++)
{
output = output.replace(matches[i], spanOpen + matches[i] + spanClose);
}
See this FIDDLE
Related
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
I am having a string like this:
"welcome country !
and some texts
Keyword1:the value
keyword2: the value2"
I want to remove keyword on undo the corresponding checkbox and also its value using Javascript. Now i could remove the keyword while undo checkbox but not the value they have entered near the keyword.
I have tried substring functions and some other, but i couldn't fix it.
my code below:
$("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
I just want to remove the texts immediately after the ":"
here is my entire code:
if ($(this).attr("data-selected1") == "true") {
$("#detailChronic").show();
$(this).attr("data-selected1", "false");
//$(".hjk").remove(":contains('" + $(this).attr("data-id") + "')");
var url = $.trim($("#txtNote").val());
str = $("#txtNote").val();
//var t = str.substring(str.indexOf(":"))
//alert(t);
//url = url.replace(/\s+/g, "\n");
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
//url.replace($(this).attr("data-id") + ":", "");
alert(url);
var temp2 = temp1.replace(/($(this).attr("data-id"))(\:(.*))/, "");
alert(temp2);
var temp1 = url.replace($(this).attr("data-id"), "");
alert(temp1);
$("#txtNote").val(temp1);
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
if ($("#selectedList").html() == "") {
$("#detailChronic").hide();
}
}
if you want to remove 'Keyword1:the value', then try
var keyWordToRemove = 'Keyword1';
var rgxStr = keyWordToRemove + ':[a-zA-Z0-9 ]*\n';
var rgx = new RegExp(rgxStr,'g');
var text = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(text);
text = text.replace(rgx,"");
console.log(text);
Hope it helps :)
You can try it using regex like this
var url = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(url.replace("Keyword1:", "test key "))
console.log(url.replace(/(Keyword1)(\:(.*))/, "$1 test value"))
you can replace Keyword1 with $(this).attr("data-id") + ":" in your code
I'm explaining my issue.
I'm trying to do a javascript function to highlight words (change their color) in an html text. I have another function to un highlight them.
I have a list of keywords that i have to highlight.
Here is the code i've writed so far
function highlight_words(keywords) {
unHighlight_words(keywords);
$('.rubricContent').each(function(index, element) {
//get elements for each rubrics
var content = $(element).html();
if (keywords) {
$(keywords).each(function(i, e) {
var term = e
var re = new RegExp('(?:[^.;\w]|^|^\\W+){0}('+ term + ' )(?:[^.\w]|\\W(?=\\W+|$)|$){0}', "gmi");
var subst = '<span style="color:red">' + term + '</span> ';
content = content.replace(re, subst);
});
$(element).html(content);
}
});
The result is not that bad my words are red colored but not when they are followed by a "." or a ","
Anyone have the solution for me ?
Thanks !!
You can use \b word boundary as follows.
term='Test';
content='TestTest. Test Test: Test. Test, TESTtest'
var re = new RegExp('(\\b'+term+'\\b)', "gmi");
var subst = '<span style="color:red">' + term + '</span> ';
content = content.replace(re, subst);
alert(content)
https://jsfiddle.net/3royvd66/1/
I want to manipulate the DOM a bit and need some help.
That's my HTML-Markup:
<span class=“content“> This is my content: {#eeeeee}grey text{/#eeeeee} {#f00000}red text{/#f00000}</span>
That's how it should be:
<span class="content">This is my content: <span style="color:#eeeeee;">grey text</span><span style="color:#f00000;">red text</span></span>
The script should replace the brackets with span tags to change the font-color.
The color should the same that is in the bracket.
My approach:
function regcolor(element) {
var text = element.innerText;
var matches = text.match(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim);
if (matches != null) {
var arr = $(matches).map(function (i, val) {
var input = [];
var color = val.slice(1, 8);
var textf = val.slice(9, val.length - 10);
var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
input.push(html);
return input;
});
var input = $.makeArray(arr);
$(element).html(input.join(''));
};
But it's not working very well and i'm not feeling good with the code, it looks messy.
And the script looses the content that's not in the brackets("This is my content:").
Anyone a idea?
I've used just a touch of jQuery, but it could easily do without. It's just a regular expression string replacement.
$('.content').each(function() {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g;
// ^ ^
// $1 $2
this.innerHTML = this.innerHTML.replace(re, function($0, $1, $2) {
return '<span style="color: ' + $1 + '">' + $2 + '</span>';
});
});
I'm using a back-reference to properly match the opening and closing braces.
Update
Could be even shorter:
$('.content').each(function() {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
repl = '<span style="color: $1">$2</span>';
this.innerHTML = this.innerHTML.replace(re, repl);
});
Look mum, no jQuery
var nodes = document.getElementsByClassName('content');
for (var i = 0, n = nodes.length; i < n; ++i) {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
repl = '<span style="color: $1">$2</span>';
nodes[i].innerHTML = nodes[i].innerHTML.replace(re, repl);
}
Use the regex to replace the matches directly:
function regcolor2(element) {
var text = element.html();
var i = 0;
var places = text.replace(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim, function( match ) {
var color = match.slice(1, 8);
var textf = match.slice(9, match.length - 10);
var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
return html;
});
$(element).html(places);
}
it can be shorter with jquery and this method or syntax
$(function() {
$('.content').html($('.content').text().replace( new RegExp('{(.*?)}(.*?){\/.*?}','g'), '<span style="color:$1">$2</span>'));
});
I feel silly asking this because I'm betting the answer is staring right at me but here goes.
I'm taking a string from the CSS style textDecoration and trying to remove the underline portion of the string (and any whitespace around it). It returns true when I run test() but when I do the replace method the string is unaltered. Help?
My code:
textDecoration = function(str) {
var n_str = str + '|/\s' + str + '|/\s' + str + '/\s|' + str + '/\s';
var nre = new RegExp(n_str, "g");
debug_log('Found or not: ' + nre.test(txt));
txt.replace(nre, '');
debug_log('Result: ' + txt);
debug_log('-----------------------');
}
var txt = "underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "underline overline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline underline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline line-through underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
Output:
replace() returns a new string with the replaces and don't change the actual string. You should do something like:
var newString = txt.replace(nre, '');
debug_log('Result: ' + newString);
test returns a boolean. replace returns a new string. It does not alter the string.
Also, your regular expression is quite odd. Applying str = "underline", you will get:
/underline|\/sunderline|\/sunderline\/s|underline\/s/
which does not match whitespaces, but "/s".