I'm trying to create a sort of "find and replace" system for my users to paste their current html and replace another website's urls with another's. Basically, i need files.enjin.com/(6 digit unique code) to be replaced with advena.io/. This is what I have already (i'm using a random's image as a temporary example):
<button id="replace">Replace</button>
<p>
Original Text:
<textarea id="input">http://files.enjin.com/435613/slider_images/slide1_1920x200.png</textarea>
</p>
<p>
New Text:
<textarea id="output"></textarea>
</p>
<script>
var mapping = {};
mapping['http://files.enjin.com/' + /(......)/i'] = 'https://advena.io/<?php echo $domain1 ?>/';
document.getElementById('replace').addEventListener('click', function(evt) {
var newString = (function(map, oldString) {
Object.keys(map).forEach(function(key) {
oldString = oldString.replace(new RegExp('\\b' + key + '\\b', 'g'), map[key]);
});
return oldString;
}(mapping, document.getElementById('input').value));
output.value = newString;
});
</script>
I know that the problem is with the expression that I'm trying to use in the first mapping. I don't know what else to use. I'm not so good with Javascript.
Thankyou in advance to anyone that can help.
Edit: I need this script to be able to change multiple occurrences of the specified mapping.
I figured it out myself. For anyone interested in the answer, here is my solution:
<button id="replace">Replace</button>
<input type="text" id="enjid" placeholder="ie. 435613">
<p>
Original Text:
<textarea id="input">http://files.enjin.com/435613/slider_images/slide1_1920x200.png</textarea>
</p>
<p>
New Text:
<textarea id="output"></textarea>
</p>
<script>
document.getElementById('replace').addEventListener('click', function(evt) {
var mapping = {};
var id = document.getElementById("enjid").value;
mapping['http://files.enjin.com/' + id + '/'] = 'https://advena.io/<?php echo $domain1 ?>/';
mapping['PHP'] = 'Personal Home Page';
mapping['JS'] = 'JavaScript';
var newString = (function(map, oldString) {
Object.keys(map).forEach(function(key) {
oldString = oldString.replace(new RegExp('\\b' + key + '\\b', 'g'), map[key]);
});
return oldString;
}(mapping, document.getElementById('input').value));
output.value = newString;
});
</script>
Related
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.
I am having trouble getting the regex to work.
Here is an html line I am working on:
<td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
Now, here is the javascript/jquery that I have at the moment:
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").text(); //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate); //put the new text back
I think I'm pretty close, but I don't have the regex right yet.
The regex ought to replace the firstname with whatever is entered in the textbox for $thisval (method is attached to keyup procedure on textbox).
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.
If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
var between = false;
$("#gentextCodeArea").contents().each(function () {
if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
if (between) return false;
between = true;
} else if (between) {
this.nodeValue = thisval;
thisval = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
What went wrong in your code
By using text() you don't get the comment tags. To get those, you need to use html() instead
replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate
It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.
Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").html(); //fetch the html
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").html(currentTemplate); //put the new text back
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
here is a function which will generate an appropriate Regular expression:
function templatePattern(key) {
return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}
the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:
'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
.replace(templatePattern('firstname'), 'Bob')
.replace(templatePattern('lastname'), 'Johnson') // "Bob Johnson"
$(function(){
function onKeyUp(event)
{
if(event.which === 38) // if key press was the up key
{
$('.firstname_placeholder').text($(this).val());
}
}
$('#firstname_input').keyup(onKeyUp);
});
input[type=text]{width:200px}
<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>
<table>
<tr>
<td ><span class='firstname_placeholder'>Harrison</span> <span class='lastname_placeholder'>Ford</span> <span class="spacer"></span></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I need to choose values in three text forms (a,b,c), for ex. 1,2,3. Then click ADD, and it will insert code like this:
<mycode a="1" b="2"><newone c="3"></newone></mycode>
How can I do it? For a while trying different approaches.
Using this code I can add new element to the page
<p> <span id="mytext">click here</span></p>
<script type="text/javascript">
function EditText() {
document.getElementById('mytext').innerHTML = '<mycode a="1" b="2"><newone c="3"></newone></mycode>';
}
</script>
But how can I edit a, b and c values using text-form?
Thank you very much!
Assuming you would also like to be able to pass the values for a, b and c to the function and output them in the newly created DOM. You could do something like the following:
function EditText(aVal, bVal, cVal) {
document.getElementById('mytext').innerHTML = '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
Appending additional elements each click:
function EditText(aVal, bVal, cVal) {
var currentInnerHtml = document.getElementById('mytext').innerHTML;
document.getElementById('mytext').innerHTML = currentInnerHtml + '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
If you have three textareas on the screen, you can get their values using JavaScript and then add them in your string instead of hardcoding them.
<textarea id="textA" cols="30" rows="10"></textarea>
<textarea id="textB" cols="30" rows="10"></textarea>
<textarea id="textC" cols="30" rows="10"></textarea>
<p> <span id="mytext">click here</span></p>
<script>
function EditText() {
var textA = document.getElementById('textA').value;
var textB = document.getElementById('textB').value;
var textC = document.getElementById('textC').value;
document.getElementById('mytext').innerHTML = '<mycode a="' + textA + '" b="' + textB + '"><newone c="' + textC + '"></newone></mycode>';
}
</script>
Below is some string, which should be serve as my HTML-Code.
I am trying from below string or HTML-Code separate the HTML-Tagname. After processing on the string the result should be something like as follows: =div=div=strong=em=p=b=p=p=h4=h1=span=.
Here is my HTML-Code in the variable "sTagName":
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
Here is my solution:
// Remove all attributes, e.g. <div style="left:100px;" > will be converted to <div>
sTagName = sTagName.replace(/<([a-zA-Z0-9]+).*?>.*?/g, '<$1>' );
// I add the "<>" at end of HTML-Code in order to remove the last useless string, I mean "Any text, "
sTagName = sTagName + "<>";
sTagName = sTagName.replace(/.*?<(.*?)>.*?/g,'=$1');
alert(sTagName);
The function alert(sTagName) delivers the expected result.
But I want improve my method referring to performance. E.g. I would like to build from two RegEx one RegEx, or something like that.
Any idea? Thanks in advance.
Use DOM:
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
tags = $("<div>").html(sTagName).find("*").map(function() {
return this.nodeName;
}).toArray();
document.write(tags);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do that:
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
var arr = new Array;
var result;
var re = /<(\w+)/g;
while ((m = re.exec(sTagName)) !==null) {
arr.push(m[1]);
}
result = '=' + arr.join('=') + '=';
console.log(result);
Try
sTagName = $.map(sTagName.split(/[^<\w+]/), function(v, k) {
return /</.test(v) ? v.replace(/[a-z]+<|</g, "=") : null
}).join("").concat("=");
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
sTagName = $.map(sTagName.split(/[^<\w+]/), function(v, k) {
return /</.test(v) ? v.replace(/[a-z]+<|</g, "=") : null
}).join("").concat("=");
$("body").text(sTagName)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<(\w+)\s*[^>]*>|.(?=([^><]*<[^>]*>)*[^<>]*$)
Try this.Replace by $1.Later on append = to each result.
See demo.
http://regex101.com/r/qZ0uP0/2
I am trying to write some code that will match words typed into a text input with words in div's with the class 'searchable' and highlights these words. What I have now works if one or more word matches and there are no words which don't match. For example, if the searchable div had the phrase: hello world and in the input was hello world it would highlight both. If the input had just hello, it would highlight that word. But if the input had hello mars, it would not highlight the word hello, because mars is not in the string. this jsFiddle demonstrates this. Any ideas much appreciated. Here is the code. Thank you.
javaScript:
if($('#search').val().length !== 0){
$('.searchable').each(function(){
var search_value = $("#search").val();
var search_regexp = new RegExp(search_value, "g");
$(this).html($(this).html().replace(search_regexp,"<span class ='highlight'>"+search_value+"</span>"));
});
}
html:
<input type = "text" id = "search" value = "hello mars">
<div class = "searchable">hello world</div>
Something like this:
// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
String.prototype.pregQuote = function()
{
return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var keyword = $("#search").val();
var searchRegex = new RegExp( '(' + keyword.pregQuote() + ')' , "ig" );
$('.searchable').each(function(){
var html = $(this).html();
html = html.replace( searchRegex , '<span class="highlight">$1</span>');
$(this).html( html );
});
Hello All Developers,
i need your help in one case so what my requirement is-
i am trying to find a String word in inner html using js like-
var index = lcBodyinnerhtml.indexOf(Searchword, 0);
so my problem is that if i am try to find a word suppose "all man " and in inner html it is
like
here in this world <i>all</i>man are
so it is not finding that word so i want that using regex or something it will skip the <> of html tag so that i 'll be able to find the exact word
Please suggest me any suitable example,thanks in advanced
You could do something like this
Html:
<div id="text">here in this world <i>all</i> man are all man</div>
Jquery / Javascript:
$(document).ready(function(){
var searchword = 'all man';
var text = $('#text').text();
var repl = '<span style="color:red">' + searchword + '</span>';
var rgxp = new RegExp(searchword, 'g');
text = text.replace(rgxp, repl);
$('#text').html(text);
});
Hope this helps!
1 minute of googling and I found this: http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
You can use the StrippedString to search for your Substring:
var OriginalString = "here in this world <i>all</i>man are"
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
// StrippedString = "here in this world allman are"