Finding commas in strings using JS - javascript

I'm trying to learn JS, so forgive me if you code makes the world explode.
Anyway, I am trying to make a tagging system interface similar to SOs. Where the user types in words and SO separates them on the comma (or on spacebar but I don't want that).
I am using jQuery to access the DOM (because it is so much easier), and I know there are various plugins that could do this and feed the homeless, but as I said I want to learn.
Here's what I have so far:
<input type="textbox" name="somebox" id"someid">
$(document).ready(function() {
var startPos = 0;
$("#someid").keyup(function() {
var inputText = $(this).val();
var commaPosition = inputText.indexOf(",", startPos);
var foundWords = [];
alert('Hello'); // even this doesn't work... why???
if (commaSearch !== '-1') {
// take the word:
foundWords.push(inputText.slice(startPos,commaPosition));
startPos = commaPosition + 1;
}
});
});
It can also be found here. Nothing seems to work, not even the alert. Any help would be grateful.

Problems:
Invalid HTML - you're missing an = in between id and "someid". This will make the alert() work.
Use String.split(',') rather than String.indexOf(','). To split and get rid of extra spaces: inputText.split(/\s*,\s*/g)
I also get Uncaught ReferenceError: commaSearch is not defined. – Felix Kling
Demo with fixes: http://jsfiddle.net/mattball/2sE8b/

Is this what you want?
DEMO
$(document).ready(function() {
$("#someid").keyup(function() {
var inputText = $(this).val();
var foundWords = inputText.split(","); // or as posted elsewhere split(/\s*,\s*/g)
if (foundWords.length>1) $("#tags").html(foundWords.join(";"))
});
});

You're going to laugh, but you didn't have the = infront of the id=someid :D http://jsfiddle.net/SuperPhil/9KVs4/2/

Is this what you want?
As Matt Ball pointed out, you're missing the = sign after id in your HTML. Next, you use commaPosition then commaSearch. Next, you use the not-identity operator with a number and a string, which will always return false.

Related

Replace function not working with javascript

How can I strip the $ and , characters from the following value, the code i am using is not working
var asset_value = second_col.find("input[type=text]").val().replace('$', '');
second_col.find("input[type=text]").val() looks like
$1,080.00
Update:
I am not sure why i am getting voted down! the duplicate solution does not solve my question, nor does any answer below, except for this, very strange!
second_col.find("input[type=text]").val(function(i, val) {
return val.replace(/\$|,/g, '');
});
var asset_value = second_col.find("input[type=text]").val();
You can use regex for this:
second_col.find("input[type=text]").val().replace(/[\$,]/g,'').
Assign this value to variable and use it.

Reassigning a value to a variable

I feel like I must be missing something really obvious here. I'm grabbing the text from within a div and using an if statement to reassign the value of the variable to "javascript" if it's "HTML", but this doesn't seem to be working at all.
Could somebody help me with this?
var currentChoice = $('#contentSelector').text();
var newChoice = currentChoice;
if (currentChoice == 'HTML') {
currentChoice = 'Javascript';
};
alert(currentChoice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentSelector"> HTML </div>
Thanks
There are spaces around 'HTML' so it's likely not matching. " HTML " is different than "HTML".
Do this and it works $.trim($('#contentSelector').text());
You have spaces either side of the HTML text value of the element. You can use trim() to remove these before testing the value in the if statement:
var currentChoice = $('#contentSelector').text().trim();
If you already use jquery, why not:
var $currentChoice = $('#contentSelector')
if ($currentChoice.text().toString() == "HTML"){
$currentChoice.text('Javascript');
};

javascript: extract parts of a string (regex)

The question is simple, assume the following string:
var str = 'aaaaab\'s'
How do you extract the value of href. I would think something like
var arr = str.match(/(?:href=")(\w+)/g) ;
--> ["href="aaaa", "href="bb"]
Of course I want
["aaaa", "bb"]
Withoug the /g it get close, but it only matches "aaaa". Any suggestions how to fix this ?
Thanks!
DOM parsing with JS is so easy.
var str = 'aaaaab\'s',
help = document.createElement('div');
helper.innerHTML = str;
Array.prototype.forEach.call(help.querySelectorAll("a[href]"), function (elem) {
console.log(elem.getAttribute('href'));
});
http://jsfiddle.net/ExplosionPIlls/gtdFh/
Because Javascript doesn't have lookbehind, this may be what you want. Naturally there will be more elegant solutions:
input.match(/<[^href|/]*(href[\s]*=[\s]*")([^"]+)(?=">)/g).map(
function(x){return x.split('href')[1].replace(/[^"]+"(.*)/,'$1');
})
Additionally, you may be better off getting a HTML parsing plugin. And extracting the properties you need using that.
Cheers.

Quotes in Javascript

I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.

Wrap every occurrence of the text "Rs." with <span class="someClass">

I have the currency "Rs." occurring on multiple places on my site. I want to wrap every occurrence of the text with <span class="WebRupee">. But if it is already wrapped with <span class="WebRupee"> it should be ignored.
I cannot use $('*:contains("Rs.")').wrap("<span class=\"WebRupee\"); because this wraps the html around the node that contains Rs. but not around the text alone. And for the same reason I cannot use .wrapInner();
Again any help will be greatly appreciated!
EDIT : the javascript provided on the webrupee site doesn't work on my site(no clue why). So that's out of the question as a solution. And hence I thought of writing a custom javascript. Just don't know how I could approach this.
EDIT(2): thinking out loud - hmm is there a way to add html at the indexOf("Rs.") ..or a simmilar approach
First, what you are trying to do is a dirty hack.
You should fix it in the source, whatever it is (for example PHP backend, Ruby backend, plain HTML, etc...).
See this example working at http://jsfiddle.net/8jXLw/
I did many assumptions and simplifications, your Regular Expressions should be more complete.
var spanit = function(item) {
var $item = jQuery(item);
var regexp = /\d+ Rs\./;
var text = $item.text();
if (!regexp.test(text)) {
return;
}
if ($item.has(".WebRupee").length) {
return;
}
var new_text = text.replace(" Rs."," <span class='WebRupee'>Rs.</span>");
$item.html(new_text);
};
jQuery(function() {
$("p.test").each(function() {
spanit(this);
});
});
Use http://cdn.webrupee.com/js file. it is working fine. i had used for one website.
If you want download and customize little..
thanks..
very inefficient solution
var replaced = $("body").html().replace('Rs.','<span class="WebRupee">Rs.</span>');
$('body').html(replaced);
var replaced = $("body").html().replace('<span class="WebRupee"><span class="WebRupee">Rs.</span></span>','<span class="WebRupee">Rs.</span>');
$('body').html(replaced);

Categories

Resources