jquery - Dynamically generate url - javascript

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

Related

How to replace certain words in a variables in 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

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
}
});

Replace text, and replace it back

I am using this code to replace text on a page when a user clicks the link. I would like a way to replace it back to the initial text using another link within the replaced text, without having to reload the page. I tried simply adding the same script within the replaced text and switching 'place' and 'rep_place' but it didn't work. Any ideas? I am sort of a novice at coding so thanks for any advice.
<div id="place">
Initial text here
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</div></span>
Where do you store the original text? Consider what you're doing in some simpler code...
a = 123;
b = 456;
a = b;
// now how do you get the original value of "a"?
You need to store that value somewhere:
a = 123;
b = 456;
temp = a;
a = b;
// to reset "a", set it to "temp"
So in your case, you need to store that content somewhere. It looks like the "source" is a hidden element, it can just as easily hold the replaced value. That way values are swapped, not just copied. Something like this:
function replaceContentInContainer(target,source) {
var temp = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
document.getElementById(source).innerHTML = temp;
}
So replace them you simply call:
replaceContentInContainer('place', 'rep_place')
Then to swap them back:
replaceContentInContainer('rep_place', 'place')
Note that this will replace the contents of the "source" element until they're swapped back again. From the current code we can't know if that will affect anything else on the page. If so, you might use a different element to store the original values. That could get complex quickly if you have a lot of values that you need to store.
How's this? I store the initial content in an element of an array called initialContent.
<div id="place">
Initial text here [replace]
</div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here [revert]
</span>
</div>
<SCRIPT LANGUAGE="JavaScript">
var initialContent = [];
function replaceContentInContainer(target,source) {
initialContent[target] = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function showInitialContent(target) {
document.getElementById(target).innerHTML = initialContent[target];
}
</SCRIPT>
Working example: http://jsbin.com/huxodire/1/
The main changes I did were the following:
I used textContent instead of innerHTML because the later replaces the whole DOM contents and that includes removing your link to replace the text. There was no way to generate that event afterwards.
I closed the first div or else all the text would be removed with the innerText including the text that works as a link.
You said you wanted to replace back to the original text, so I used a variable to hold the last value only if this existed.
Hope this helps, let me know if you need more assistance.
The div tags were mixed up and wiping out your link after running it. I just worked with your code and showed how you could switch.
<div id="place">
Initial text here
</div>
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML =
document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div>
<div class="text" onClick="replaceContentInContainer('place', 'original_place')">
<u>Link to restore text</u></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</span>
<span id="original_place">
Initial text here
</span>
</div>

Textarea formatting lost during copy

Problem:
After formatting text in a textarea, formatting is lost when copying to another textarea, whether by code or by mouse copy through ctrl-drag.
Details:
To prove the issue, I have a simple html page with no CSS, and a javascript function that formats the text by removing line breaks, using . I copy text from Notepad to my webpage's textarea1. I run the javascript function. This function replaces all carriage returns with "". The function runs correctly, with no errors. After running, all carriage returns have been removed from the text in textarea1. I can confirm they've been removed by running a function that copies the text from textarea1 to textarea2.
But, the weirdness comes next. After formatting textarea1, when I select all text and ctrl-drag (to copy) the text to textarea2, the original text is copied, with carriage returns back in place exactly where they were at before. The same happens if I copy-paste. What's going on?
Setup:
Win 7 machine, running IE9.
Code:
HTML...
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
<!--scripts-->
<script src="jquery-2.1.1.min.js"></script>
<script src="text_edit_test.js"></script>
</head>
<body>
<h1>Service Notes Text Editor</h1>
<textarea id="textarea1" cols="60" rows="11"></textarea>
<br>
<button type="button" id="buttonRemoveCR">Format Text</button>
<button type="button" id="buttonCopyText">Copy Text</button>
<br>
<textarea id="textarea2" cols="60" rows="30"></textarea>
</body>
</html>
... and javascript...
// make sure doc ready first
$(document).ready(function(){
//format Text
$("#buttonRemoveCR").click(function(){
var myText = "";
var myTextRes = "";
myText = $("#textarea1").html();
//remove all char returns
myTextRes = myText.replace(/\r/, "");
//change text in textarea1 so no carriage returns
$("#textarea1").html(myTextRes);
});
//copy Text
$("#buttonCopyText").click(function(){
var myText = "";
myText = $("#textarea1").html();
$("#textarea2").html(myText);
});
});
// make sure doc ready first
$(document).ready(function(){
//format Text
$("#buttonRemoveCR").click(function(){
var myText = "";
var myTextRes = "";
myText = $("#textarea1").val();
//remove all char returns
myTextRes = myText.replace(/(?:\r\n|\r|\n)/g, '')
//change text in textarea1 so no carriage returns
$("#textarea1").val(myTextRes);
});
//copy Text
$("#buttonCopyText").click(function(){
var myText = "";
myText = $("#textarea1").val();
console.log(myText);
$("#textarea2").val(myText);
});
});
Use x.val() to get the content of textarea x and x.val(text) to set the contents of textarea x -- textareas ignore their inner HTML.

Categories