I want to highlight in a text all the occurrences from a word that I have in my URL.
For the first occurrence everything works fine. But I don't know how to go to the next one.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(searchText, "<mark>" + searchText + "</mark>");
el.innerHTML = marked;
}
}
I have tried to add a while(window.find(searchText) before the if but it doesn't work, it seems to loop only on the first occurence of my word.
Thanks in advance
If you're not using regex then it'll only replace the first occurrence, you might try this, Also modify the regex as per your needs.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(
RegExp(`(${searchText})`),
"<mark>" + searchText + " </mark>");
el.innerHTML = marked;
}
}
Note: The match is case sensitive
Related
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var value = 10;
How do I replace the &filters[]=price_gte:20 part with the new path? (path + value)
I've tried RegExp():
var re = new RegExp(path);
console.log(url.replace(re, ''));
//returns http://mywebsite.com/?&filters[]=price_gte:20
That didn't even work, let alone adding the digit in the regex. Problem is, price_gte is a variable (and so will price_lte be, and whatever other ranges there might come), with a variable digit after it.
Information I have:
url (http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100)
path (&filters[]=price_gte:)
new value (10)
Desired result:
http://mywebsite.com?&filters[]=price_gte:10&filters[]=price_lte:100
What am I missing?
You were almost there, just needed to escape the brackets:
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var regexPath = '&filters\\[\\]=price_gte:\\d+';
var value = 10;
var re = new RegExp(regexPath);
console.log(url.replace(re, path+value));
Perhaps you meant this
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = 'filters[]=price_gte:';
var value = 10;
var re = /filters\[\]=price_[g|l]te:\d+/;
alert(url.replace(re,path+value))
However a better solution might be
// from http://stackoverflow.com/a/20420424/295783
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1' + paramValue + '$2');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var value=10;
url = replaceUrlParam(url,"filters[]", 'price_gte:'+value);
alert(url)
This seems to work for me:
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/&filters\[\]=price_gte:\d+/, "&filters[]=price_gte:" + value);
alert(newStr);
}
This is enough for getting new value
var str = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100';
var pattern = /price_gte:\d+/;
var new_value = 10;
str = str.replace(patter, 'price_gte:'+new_value);
And Simple Solution will be =>
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/(\w*)(price_gte:)(\d*)/i,"price_gte:"+ value);
alert(newStr);
}
I have been struggling with a script I have been working on for a while. The problem is that when I run the script with text like:
Hi. apples are amazing.
I want to make only the a in apples capitalized, but instead the text comes out as:
Hi. Apples Are Amazing.
Here is the code:
function caps()
{
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText()
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lower = "abcdefghijklmnopqrstuvwxyx";
//while (() != null) {
//var search = text.findText('. a')
//var start = replace - 1
//text.deleteText(start, replace)
//text.insertText(start, " A")//}
for(var i=0; i<caps.length; i++)
{
var nextCaps = caps.charAt(i);
var nextLower = lower.charAt(i);
while (text.findText('. ' + nextLower) != null)
{
Logger.log(nextLower)
Logger.log(nextCaps)
var search = text.findText('. ' + nextLower)
var replace = search.getEndOffsetInclusive()
var start = replace - 1
text.deleteText(start, replace)
text.insertText(start, " " + nextCaps)
}
//var nextChar = caps.charAt(i);
//Logger.log(nextLower)
}
}
Basically, the code looks for ". a" and replaces it with ". A" (same with b, c, d and so on). If anyone can help me with this it would be very much appreciated.
The below code follows your example where you want to capitalize the first letter after the end of the first sentence. So long as that is the case this regex and replace will do that for any letters.
var str = 'Hi. apples are amazing.';
var reg = /\.\s./;
function replacement(match) {
return match.toUpperCase();
}
str = str.replace(reg, replacement);
Logger.log(str);
I am attempting to do a quick replace of the 'innerHTML' of the 'code' element. I thought this may work:
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
code.replace(codeExam1, '<');
code.replace(codeExam2, '>');
}
Do I need to perform any additional steps to push the information back to the browser or conversion of data types maybe? Or am I completely wrong in how 'RegEx' and 'innerHTML' work? I appreciate the feedback in advance.
So, first fo all:
var code = document.getElementsByTagName('code').innerHTML;
document.getElementsByTagName returns a list of elements not just one. So, if your purpose is escaping all the code tags you have in the page, you need to iterate them.
Second, I believe you can avoid regexp just using textContent (where supported) or innerText.
var codes = document.getElementsByTagName("code");
for (var i = 0, code; code = codes[i++];) {
if ("textContent" in code)
code.textContent = code.innerHTML;
else if ("innerText" in code)
code.innerText = code.innerHTML;
}
or create a new text node:
var codes = document.getElementsByTagName("code");
for (var i = 0, code, html; code = codes[i++];) {
html = code.innerHTML;
code.innerHTML = "";
code.appendChild(document.createTextNode(html));
}
That's should escape every html entities. If you still want to use the regexp, maybe as fallback, you can have this kind of function:
var escapeEntities = (function(){
var entities = {"<" : "lt", ">" : "gt", "&" : "amp" };
var re = new RegExp("[" + Object.keys(entities).join("") + "]", "g");
function replaceEntities(match) {
return match in entities ? "&" + entities[match] + ";" : match;
}
return function(value) {
return value.replace(re, replaceEntities);
}
})()
And then in your code:
code.innerHTML = escapeEntities(code.innerHTML);
Note that if Object.keys is not supported you can easily use a shims (as indicated in the link); or simply replace manually the list of entities you support:
var entities = {"<" : "lt", ">" : "gt", "&" : "amp" };
var re = /[<>&]/g;
In that case you need to remember to add in both entities and re variables a new entity you want to support in the future; Object.keys just help you in maintenance.
Use assignment:
code = code.replace(codeExam1, '<');
code = code.replace(codeExam2, '>');
And modify your code like this:
function codeDisplay ( ) {
var codeArray = document.getElementsByTagName('code');
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
for ( var i = 0 ; i < codeArray.length ; ++i ){
var code = codeArray[i].innerHTML;
code.replace(codeExam1, '<');
code.replace(codeExam2, '>');
codeArray[i].innerHTML = code;
}
}
Replace returns a new string containing the result. See MDN for example.
To actually replace the contents of code you code has to look like this:
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
code = code.replace( codeExam1, '<');
code = code.replace(codeExam2, '>');
document.getElementsByTagName('code').innerHTML = code;
}
Or a shorter version (could be even shorter, but in my opinion just at the cost of readability):
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
code = code.replace( /</gm , '<' )
.replace( />/gm, '>' );
document.getElementsByTagName('code').innerHTML = code;
}
Try this:
function codeDisplay ( ) {
var s = document.getElementsByTagName('code').innerHTML;
s = s.replace(/\</g,'<');
s = s.replace(/\>/g,'>');
document.getElementsByTagName('code').innerHTML = s;
}
I want to count number of occurence of BB code like word (example: [b] [/b]).
I tried
(str.match(/\[b\]/g) str.match(/\[\/b\]/g))
None of this worked, please help !!!
Edit
document.getElementById('textarea').value = 'HIiiiiiiiiiii [b]BOld[/b]';
var str = document.getElementById('textarea').value;
Answer:
if (str.match(/\[b\]/g).length == str.match(/\[\/b\]/g)).length) {alert("Fine");}
This regex will match a BB code opening tag:
str.match(/\[[a-z]*\]/g)
Edit: Here's some code that will do exactly what you want including creating an array of errors listing all missing closing tags. This code uses the underscore library for the groupBy() call.
jsFiddle
var bbcode = 'HI[i]iii[i]iii[/i]iii [b]BOld[/b] yahhh [img]url[/img]';
var matches = bbcode.match(/\[[a-z]*\]/g); //get the matches
var tags = _.groupBy(matches, function(val) {
val = val.substring(1, val.length-1);
return val;
});
var errors = [];
for (var tag in tags) {
var regex = '\\\[/' + tag + '\\\]';
if (bbcode.match(regex).length != tags[tag].length) {
errors.push('Missing a closing [/' + tag + '] tag');
}
}
console.log(errors);
Replace occurences until there aren't any; keep track of the amount on the way:
var regexp = /\[[a-z]\](.*?)\[\/[a-z]\]/i;
var str = "test [b]a[/b] test [i]b[/i] [b]d[/b] c";
var newstr = str;
var i = 0;
while(regexp.test(newstr)) {
newstr = newstr.replace(regexp, "");
i++;
}
alert(i); // alerts 3
i want to strip just text values from below html with js.
var Str = "<span style="">MY name is KERBEROS.</span><B>HELLO Everbody</B>"
All text strips with codes that is below;
[^<>]+(?=[<])
But i want to strip just UPPERCASE words. Clresult must be: MY, KERBEROS, HELLO
Thank you already now for your suggestions.
Regards,
Kerberos
Here is your code, gives output: MY,KERBEROS,HELLO
<script>
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "");
};
String.prototype.getUpperCaseWords = function()
{
var matchTag1 = /\b([A-Z])+\b/g;
var o = this.match(matchTag1);
return o;
};
var Str = "<span style=''>MY name is KERBEROS.</span><B>HELLO Everbody</B>";
var out1 = Str.stripHTML();
var out2 = out1.getUpperCaseWords();
alert(out2);
</script>
This is another solution in JavaScript using just one line of regex:
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "").match(/\b([A-Z])+\b/g);
};
var Str = "<span style=''>MY name is SATYA PRAKASH.</span><B>HELLO Everyone</B>";
var out1 = Str.stripHTML();