How to replace certain words in a variables in JavaScript - javascript

The code below works very fine and replaces certain variables in the div. Eg food is replaced by bolded food is ready etc.
<script>
$(document).ready(function(){
$('div').html( $('div').html().replace(/food/g, '<strong>food is ready</strong>') );
$('div').html( $('div').html().replace(/meat/g, '<strong>good meat</strong>') );
$('div').html( $('div').html().replace(/milk/g, '<strong>best milk</strong>') );
});
</script>
<div> hello do you have food, what about meat. I will also need milk. and please make them bold.</div>
Here is my issue: I want to implement the same functionality above using inputted data from form variables. Eg. I want if type certain words and it contains food, milk etc. let them be replaced with their bolded equivalents in the sentence as I type. I have tried the code below but cannot get it to work.
<script>
$(document).ready(function(){
$('.message').keyup(function(){
var message = $('.message').val();
$('.result').html( $('.message').html().replace(/food/g, '<strong>food is ready</strong>') );
$('.result').html( $('.message').html().replace(/meat/g, '<strong>good meat</strong>') );
$('.result').html( $('.message').html().replace(/milk/g, '<strong>best milk</strong>') );
});
});
</script>
<input type='text' id='message' class='message'>
//Display all the typed sentence and replace their matched word with their bolded equivalents
<div class="result"></div>
</script>

I didn't test the following code but it should work fine.
<script>
$(document).ready(function(){
$('.message').keyup(function(){
var message = $('.message').val();
var output = message.replace(/food/g, '<strong>food is ready</strong>').replace(/meat/g, '<strong>good meat</strong>').replace(/milk/g, '<strong>best milk</strong>'); //chained replace()
$('.result').html( output );
});
});
</script>
<input type='text' id='message' class='message'>
//Display all the typed sentence and replace their matched word with their bolded equivalents
<div class="result"></div>
</script>
The two problems were:
using unchained replacing functions when setting the output value, causing overriding old rules
using $('.message').html() instead of message

Related

How to make javascript regular expression match any char and carriage return?

I have a html file like below.
<body>
<p>Enter your phone number with area code and then click
Check The expected format is like</p>
<form action="#">
<input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
</form>
</body>
</html>
I use below script which can print right result.
fs.readFile('test.html', 'utf8', function (err, data) {
var re = /<p>[a-zA-Z1-9\s\r\n]*<\/p>/i;
var myArray = data.match(re);
console.log(myArray);
});
the result: '<p>Enter your phone number with area code and then click \r\n Check The expected format is like</p>'
But I want to use regular expresstion like below.
re = /<p>[.\r\n]*<\/p>/i;
But it print null. How to fix it? Why I can not use . to replace a-zA-Z1-9\s thanks.
The reason is that a dot within a character class ([...]) looses its "superpowers" - meaning it is only a dot.
What you possibly want is re = /<p>[\s\S]+?<\/p>/i; but please be warned that it is nod advisable to parse HTML structures with a regular expression:
let html = ` <body>
<p>Enter your phone number with area code and then click
Check The expected format is like</p>
<form action="#">
<input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
</form>
</body>
</html>`;
re = /<p>[\S\s]+?<\/p>/i;
var myArray = html.match(re);
console.log(myArray);

Convert decimal HTML entities to unicode characters from string

I have an extract html file from a comment system I have to use that looks like this:
<div>Plz say my name&#128516;&#9996;&#127995;</div>
<div>Dose Amelia like donuts &#127849;&#127849;</div>
Obviously the part to note is all the emoji. I then pull that HTML file in using
var questionsfile = "comments.inc";
$.get(questionsfile, function(response) {
$(".noquestions").replaceWith(response);
});
I used .replace() to convert it back to ✌ but it now just outputs it as plain text. How do I make it so that the response output contains ✌🍩?
You need to replace its text as its html, check the demo below
var str = `<div>Plz say my name&#128516;&#9996;&#127995;</div>
<div>Dose Amelia like donuts &#127849;&#127849;</div>`;
var $str = $( str );
$str.find( "div" ).each( function(){ //iterate each div
$(this).text( $(this).html() ); //replace text with html
})
$(".noquestions").replaceWith( $str );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="noquestions-wrapper">
<div class="noquestions">
assasd
</div>
</div>

how to get only numbers inside tags leaving texts

here is my p iam intrested in only phone numbers not texts
<p class="phone-list">
<span>hello</span>
<span>8046033006<script type="text/javascript"> whicVer('vers1');</script></span>
</p>
<p class="phone-list">
<span>hello</span>
<span>12345566<script type="text/javascript"> whicVer('vers2');</script></span>
</p>
I wanted to get only phone number, ie. 8046033006 & 12345566 through this code I am getting
$('.phone-list span:nth-child(2)').each(function()
console.log($(this).text());
);
the output looks like something....
8046033006 whicVer('vers1')
12345566 whicVer('vers2')
I have observed why script tag is not printing? Please help me thanks in advance
You can use regex. Or just use a little span just around the number.
var removedText = initialText.replace(/\D/g, '');
For your case it would be:
$('.phone-list span:nth-child(2)').each(function() {
var num = $(this).text().replace(/\D/g, '')
console.log(num);
);
Here is a little JSFiddle
Assuming the HTML structure is the same for all .phone-list elements, you can retrieve the first textNode from the second child span and get it's nodeValue. Try this:
$('.phone-list span:nth-child(2)').each(function() {
console.log($(this).contents()[0].nodeValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="phone-list">
<span>hello</span>
<span>8046033006<script type="text/javascript">//whicVer('vers1');</script></span>
</p>
<p class="phone-list">
<span>hello</span>
<span>12345566<script type="text/javascript">//whicVer('vers2');</script></span>
</p>
Note that I only commented out the whicVer() function calls as they were giving errors in the snippet.
Once you get the text from the DOM , you can use regex like this
// text from which number will be seperated
var number = "8046033006hriughidhgiudhgiudthgiuhdiutg"
document.write('<pre>'+number.match(/\d+/)[0]+'</pre>')
JSFIDDLE

jQuery: find words in a textarea paragraph and replacing it with word

I'm trying to translate a text/paragraph from its original English version to valley girl talk. So for instance, "hi" will be "hellloooooo, what is up?". The words have been entered into a database with the English word and its translated valley girl version. Example: English column-> hi, VG column-> hellloooooo, English-> yes, VG -> like, hells yes
I am using MySQL to get the translated words off the database and returning a json.
So this is how I'm retrieving it in AJAX:
$.ajax({
type: "GET",
url: "dictionary.php",
success: function(data) {
var json = JSON.parse(data);
// replacing all the ing's with in'
$("#textarea").each(function(){
var ing = $(this).val().replace(/ing/g,"in'");
$(this).val(ing);
// finding the English words and replacing with VG
$.each(json, function(idx, obj) {
var vg= $("#content").val().replace(/obj.english/g, obj.vg);
$("#textarea").val(vg);
);
});
}
});
I got the "ing" replacements well and working but trying to replace the valley girl words is a no go. Am I looping through the json objects incorrectly?
EDIT: here is the json data
[{"english":"hi","0":"hi","vg":"hellloooooo!","1":"hellloooooo"}, {"english":"yes","0":"yes","vg":"like, hells yes","1":"like, hells yes"},.....]
please see this small example of replacing the words, then outputting this to a new field, this may help with what you want to achieve.
it loops over each word and goes for an exact word match, you may run into issues if some of the translations also contain words in english
$(document).ready(function(){
var json = [{"english":"hi","0":"hi","vg":"hellloooooo!","1":"hellloooooo"}, {"english":"yes","0":"yes","vg":"like, hells yes","1":"like, hells yes"}];
var userInput = $('#textarea').val();
json.forEach(function(word){
console.log(word);
userInput = userInput.replace(new RegExp("\\b"+word.english+"\\b","g"),word.vg);
});
$('#translation').val(userInput);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<textarea id="textarea">
hi this is a test of yes translation. hi yes
</textarea>
<textarea id="translation">
</textarea>
</body>
</html>
Your code seems to have several logical mistakes. You're looping over a jQuery selection where an id is used? An id is always treated as unique regardless of what you do, hence it's called id :) Then you're replacing the value of the html element every time (which just happens to be once in this case but that's a mistake on your part I assume).
I changed your html a bit so that your code will work correctly.
HTML:
<textarea class="text">
hi this is a text area what is going on? hi how are you? yes, I am fine.
</textarea>
<textarea class="text">
hi this is a text area what is going on? hi how are you? yes, I am fine.
</textarea>
JavaScript/JQuery:
$.ajax({
url: "dictionary.php",
type:"GET",
success: function(data) {
//store the parsed json
var json = JSON.parse(data);
//loop through the .text elements
$(".text").each(function(){//begin outer each
//reference the current object
var that = $(this);
//replace the all of the ing's with in'
var ing = $(this).val().replace(/ing/g,"in'");
$(this).val(ing);
// finding the English words and replacing with VG
$.each(json, function(idx, obj) {//begin inner each
//Create a new regular expression that matches the word only.
var regExp = new RegExp("\\b" + obj.english,"g");
//Replace the value of the text value with the vg value and store it.
var vg = that.val().replace(regExp, obj.vg);
//Replace the value of the .text text area in the dom.
that.val(vg);
});//<-- was missing a closing } bracket. //end inner each
});//end outer each
}
});

jquery - Dynamically generate url

I am trying to dynamically create a url slug when a user types into an input. Unwanted characters should be removed. Spaces should be replaced by hyphens and everything into lowercase. So if a user types "Ruddy's Cheese Shop" it should render "ruddys-cheese-shop".
This is what I have so far.
<input id="tb1" />
<div id="tb2"></div>
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$('#tb2').html($('#tb1').val(Text));
});
It almost works but I am new to js. Thanks
Your code but slightly improved.
$('#tb1').keyup(function() {
var text = $(this).val().toLowerCase();
text = text.replace(/[^a-z0-9]+/g, '-');
$('#tb2').text(text);
});
You don't need to find $('#tb1') element over and over again since you have a refference to it inside the function as $(this).
http://jsfiddle.net/jFjR3/
It looks ok except where you set the #tb2 value. I think you want:
$('#tb2').html(Text);
Of course, remember since you've called toLowerCase, you don't need to replace upper case chars. Rather a simpler regexp:
Text = Text.replace(/[^a-z0-9]+/g,'-');
If you also want to update the edit field as the user types, here's a full example. Note that it will only update #td2 when you start typing.
<html>
<head>
<script src="js/jquery.js" ></script>
<script language="javascript">
$(function() {
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-z0-9]+/g,'-');
$('#tb2').html(Text);
$('#tb1').val(Text);
});
});
</script>
</head>
<body>
<input type="text" id="tb1" value="Ruddy's Cheese Shop" />
<div id="tb2"></div>
</body>
</html>
Looks like you need to run a couple of replaces i.e.
Text = Text.replace(/[\s]+/g,'-');
Text = Text.replace(/[^a-z_0-9\-]+/g,'');
That converts ruddy's Cheese Shop to ruddys-cheese-shop
Hope that helps

Categories