Replacing a substring of an element's text with another string - javascript

The Problem
I'm trying to use the JavaScript string replace method to replace some text in a div if it contains a certain string. However, my code does not replace the string inside that div.
The Javascript
function john(){
var NAME = "Johnny Buffet,";
var val = $("div#like-list-").text();
if ( val.indexOf(NAME) !== -1 ){
val.replace(NAME, '');
}
}

It doesn't work because .replace() is a String function and not a jQuery function; Strings in JavaScript are immutable, so .replac() returns the modified String which you then have to reassign to your element.
That said, you can use .text(fn) to perform the replacement in a single step:
$("div#like-list-").text(function(i, val) {
return val.replace(NAME, '');
});
Btw, I've removed the .indexOf() condition as well, because if NAME doesn't occur inside your string, the .replace() function will just return the original string.

You're editing the string, then simply throwing it away. Take the edited val and put it's contents back into the HTML element using a parameterized call to the text method.
function john(){
var NAME = "Johnny Buffet,";
var val = $("div#like-list-").text();
if ( val.indexOf(NAME) !== -1 ){
$("div#like-list-").text(val.replace(NAME, ''));
}
}

replace() is javascript not jQuery and you need to reset the value to variable after replace as replace() returns the updated text;
ie;
val = val.replace(NAME, '');
so try:
function john(){
var NAME = "Johnny Buffet,";
var val = $("div#like-list-").text();
if ( val.indexOf(NAME) !== -1 ){
val = val.replace(NAME, '');
}
}

Related

HTML DOM check if the text of an element includes specific text?

How to check if an element's innerHTML includes "as me to" (the whole phrase and not just if it includes one of the words)?
I know that it is pretty short, but the question is already stated in the title.
you can use indexOf()
var str = $('some selector id').innerHTML();
var result = str.indexOf("as");
if result is -1 then there is no instance of "as" in the given string.
You can check it using RegExp. If the element has given string, the test() function will return true or false if it's not.
function check(elem, str) {
var element = document.getElementById(elem).innerHTML,
rg = new RegExp(str, 'g'),
res = rg.test(element);
console.log(`Does the ${elem} element contains ${str} - ${res}`);
return res;
}
check('p', 'as');
check('p', 'something');
<p id='p'>ashamed</p>
Try this!
HTML
<div id="source">this word as </div>
JAVASCRIPT
var sourceEl = document.getElementById('source');
if (sourceEl.textContent.includes('as'))
{
alert("Exist");
}
https://jsfiddle.net/n3zkzy1g/5/

JavaScript - Replace some letters with numbers

I'm trying replace some letters with numbers in JQuery, and I have initialized my object like this:
var myVar = {'a':1, 'b':2, 'c':3, 'd':4}
I'm getting the string from an input and I want to convert these letters immediately as the user is typing in text input. I want to do it via RegEx.
You can use input event, String.prototype.replace(), RegExp() with parameter new RegExp(keys.join("|"), "g" where keys are property names of myVar object
var myVar = {"a":1, "b":2, "c":3, "d":4};
var keys = Object.keys(myVar);
document.querySelector("input")
.addEventListener("input", function(e) {
e.target.value = e.target.value.replace(new RegExp(keys.join("|"), "g")
, function(match) {
return myVar[match]
});
});
<input type="text" />
Use :
Event : keyup event
Action :split & join for String AND map for Array.
$(INPUT_SELECTOR).keyup(function(event){
var newVal=$(this).val().split('').map(function(ch){
if(isFinite(ch) || !myVar[ch]){
return ch;
}else{
return myVar[ch];
}
}).join('');
$(this).val(newVal);
})
DEMO

access elements in array of strings that contain certain strings

I have an array that can look like this: ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"]
I want to access the element containing IN, if it exists and the next elements(s) until I reach and including an element with NN in it. and join those elements together into a string.
When I try to access the element containing IN like so, I get -1 that there is no element containing IN.
Here's how I am trying to do it:
strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
strARR[strARR.indexOf('IN')];
but then I get undefined because nothing at -1 exists.
How can I access the element of this array of strings if it contains IN and every element after until it matches an element containing NN, including that element? And joining those as a string?
You need a for loop for that:
var strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
var foundStr = null;
for (var i = 0, cString; i < strARR.length; ++i) {
cString = strARR[i];
if (cString.indexOf("IN") !== -1) {
foundStr = cString;
break;
}
}
if (foundStr !== null) {
/* do someting with found string */
}
strARR[strARR.indexOf('IN')] was returning a weird value because:
strARR.indexOf('IN') // returns -1 (no string "IN" in the array)
strArr[-1] // undefined
There is no "IN" element in that array. Just an "inIN" element, which is not precisely equal. (Keep in mind, this could be an array of ANYTHING, not just strings, so it's not assumed they can check the string contents)
You'll have to loop through the strARR, using a standard for(var i = 0; i < strARR.length; i++) loop. The i variable will help you find the correct indexes.
Then, for combining the results, use the Array.splice and Array.join methods. Splice can take a start index and length of items to take as arguments, and Join can take an intermediate character as an argument, like a comma, to put between them.
You need to evaluate each element in the array individually, not evaluate the array as a whole. Using jQuery each, you can do:
var containsIN = '';
$.each(strARR, function(){
if($(this).indexOf('IN') !== -1){
containsIN = $(this);
}
});
To achieve appending or joining string until you find a string that contains 'NN'
you need to modify the original if condition to:
if(containsIN === '' && $(this).indexOf('IN') !== -1)
then add another condition afterwards
if(containsIN !== ''){
final += $(this);
}
Then, to terminate the each:
if($(this).indexOf('NN') !== -1){
return false;
}
So, the final code should look like:
var containsIN = '';
var final = '';
$.each(strARR, function(){
if(containsIN === '' && $(this).indexOf('IN') !== -1){
containsIN = $(this);
}
if(containsIN !== ''){
final += $(this);
}
if($(this).indexOf('NN') !== -1){
return false;
}
});
You can use the Array's filter() function for this. There is a polyfill available on the linked page if you need to target browsers that do not support filter() natively.
You can create any filter condition that you like and filter() will return the array elements that match your condition.
var strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
var strARRFiltered = strARR.filter(function(element){
return element.indexOf("IN") !== -1;
});
alert(strARRFiltered);
Here is an example of this concept expanded a bit to include accessing multple matches and a variable filter.
To do what you're currently trying to do, the code would need to be like this:
strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
strARR[strARR.indexOf('inIN')];
You need to loop through each element in the array calling indexOf, rather than trying to access it as an array.

JS: how to get resulting value out of its function?

I process a string, and want to get the end result out of the function so the next function can reuse it. Basically, I currently approach is such:
function pre_processing(str){
str = str.replace(/\d/g, ""); // delete all digit (a simplier example than my code)
return str;
}
function post_processing(){
// do processing n⁰2 on var str
}
pre_processing("w0rd2");
console.log(str) // fails! Uncaught ReferenceError: str is not defined
post_processing(str); // fails, haven't input
This doesn't works. What does I do wrong ? is it a return not done right, or related to asynchroneous JS ? Other ? 2. How to do it right ?
Full JS code there : http://jsfiddle.net/hugolpz/CYwD3/7/ (I made it as simple as possible)
The function then equals that return value, so:
var str = pre_processing("w0rd2");
Your "pre_processing" function returns a string, but you're paying no attention to the return value:
var str = pre_processing("w0rd2");
Now you have a variable called "str" outside the functions.
Of course you can just apply the second function directly to the result of the first:
console.log( post_processing( pre_processing("w0rd2") ) );
You have to assign it to a var when it returns, because the function has now assumes the value of the evaluation, so
var newStr = pre_processing("w0rd2");
Also, shorten your function up with this
return str.replace(/\d/g,"");
instead of str = str.replace(/\d/g,""); return str;
and finally
var newStr = post_processing(newStr);

jQuery to Select elements that does not contain a certain value

I am using the following jQuery code to count the number of text fields that have a value that is the same as its title attribute.
$(".textfield").val( $(".textfield").attr('title') ).size();
Problem: How do I count the number of text fields that do not have a value equal to its title attribute?
First of all, the code you post is not doing what you say it does. This:
$(".textfield").val( $(".textfield").attr('title') ).size();
Will set the value of all elements with class ".textfield" to the title of the first ".textfield" element's title attribute, and then return a count of all of them.
You need to compare the return of the .val() method (with no parameter it returns the current value) with the return of the .attr('title') method. You can do this with .filter() and then check the .length of the resulting jQuery object:
$('.textfield').filter(function() {
var $this = $(this);
return $this.val() == $this.attr('title');
}).length;
And then to get a count of those where the value is not equal just do the same thing except with != instead of ==. So:
$('.textfield').filter(function() {
var $this = $(this);
return $this.val() != $this.attr('title');
}).length;
(Note that .length will give you the same count as .size() but without the overhead of a function call.)
I would use filter() and then access the length property of the returned set.
var count = $('.textfield').filter(function() {
return $(this).val() != $(this).attr('title');
}).length;
You could also probably get away with the body of filter() as return this.value != this.title.
use the filter function.
use length property of the selector
var length = $('.textfield').filter(function() {
return this.value != this.title;
}).length;

Categories