remove first match from string in javascript and jquery - javascript

I have string like this 'set , many, like, see, what'
when i create this string i also create div with linked element
<div>
set
many
like
...
</div>
and also create hidden input with 'set , many, like, see, what' value ... when we click on linked element we have string of link ( example: set )
how remove first match of string and strip it from hidden input?
ps: i said first match because one element can repeat

Where link is a reference to one of the links, theString is a reference to your string, and hidden is a reference to your hidden input control, you can do something like this:
link.onclick = function(e)
{
var expr = new RegExp("\b" + this.innerHTML + "\b(, ?)?");
theString = theString.replace(expr, "");
hidden.value = theString;
}

var anchors = document.getElementById('container').getElementsByTagName('a'),
hiddenInput = document.getElementById('hidden');
for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
var term = anchor.innerHTML;
hiddenInput.value = hiddenInput
.value
.replace(new RegExp(term + ',\s?'), '');
}
}
This code allows you to click one of those anchors, in which it will remove the first occurrence of the anchor's text node, and the , and any optional whitespace character.

Related

How to remove html tag from string but keep html entities intact

I would like to remove the HTML tags (element) from a string without touching the html entities such as &nbps; & é < etc..
For now I am using this :
stringWithTag = "<i> I want to keep my -> <- element space, but remove the tags <b>Please Help</b></i>";
var div = document.createElement('div');
div.innerHTML = stringWithTag;
console.log("INPUT with html entity ");
console.log(stringWithTag);
htmlNoTag = div.textContent || div.innerText || "";
console.log("\nOUTPUT that should still have entity , but not...");
console.log(htmlNoTag);
cf jsfiddle : https://jsfiddle.net/az4st8LL/
But I always miss the element entity (in that exemple &nbsp should still be visible but it is not the case).
I would like to avoid using a regex to remove all html tags if possible.
Does anyone has a solution to this ?
Thanks,
Since you want to avoid using regex, try
function stripTags(html) {
var result = "";
var add = true, c;
for (var i = 0; i < html.length; i++) {
c = html[i];
if (c == '<') add = false;
else if (c == '>') add = true;
else if (add) result += c;
}
return result;
};
This will not work for
<i>I want to keep my -> <- element space, but remove the tags <b>Please Help</b></i> since you used < and > but will turn <i> I want to keep my element space, but remove the tags <b>Please Help</b></i> into I want to keep my element space, but remove the tags Please Help
You might want to consider using a regex anyway (stolen from this answer):
string.replace(/<(?:.|\n)*?>/gm, '')
stringWithTag = "<i> I want to keep my element space, but remove the tags <b>Please Help</b></i>";
console.log(stringWithTag.replace(/<(?:.|\n)*?>/gm, ''));
I cheated a little bit by removing the "->" and "<-" from your string - since the regex matches everything between "<" and ">", those characters broke the demo.
You can use a regex that searches for tags and reverse it. Then replace your string with this regex and encodeURIComponent values. Then you can decodeURIComponent when you need to use it.
var stringWithTag = "<i> I want to keep my -> <- element space, but remove the tags <b>Please Help</b></i><i> I want to keep my -> <- element space, but remove the tags <b>Please Help</b></i><i> I want to keep my -> <- element space, but remove the tags <b>Please Help</b></i><i> I want to keep my -> <- element space, but remove the tags <b>Please Help</b></i>";
var tags = stringWithTag.match(/(<[^>]>|<\/[^>]>)/g);
var startIndex = 0;
var str = "";
tags.reduce(function(p,c){
var i = stringWithTag.indexOf(p, startIndex)+ p.length;
var j = stringWithTag.indexOf(c, startIndex);
str += p+ encodeURIComponent(stringWithTag.substring(i,j)) + c;
startIndex = j;
return c
})
var div = document.createElement('div');
div.innerHTML = str;
//console.log("INPUT with html entity ");
//console.log(stringWithTag);
htmlNoTag = div.textContent || div.innerText || "";
//console.log("\nOUTPUT that should still have entity , but not...");
console.log(decodeURIComponent(htmlNoTag));
Reference
encodeURIComponent
decodeURIComponent

String manipulation using javascript

I am working on some string manipulations using javascript.I have a senario where i need to do a search in the string and remove certain words.
Here is my senario:
When i click 'Click me' it should look for the word in the input from the string variable,
and if matching found it should remove that word from the input.
Here is my sepecial senario, while removing the word from the input, it should remove the : and the integer value and comma (if available) which is there before the matching word.
In my example input is 1:first user,2:second user in the text box
i need the output as 2:second user
How can i achive this
<input id='textinput' type='text' value='1:first user,2:second user'></input>
<div class='click'>Click me</div>
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
$('#textinput').val().replace(/string/g, '');
});
});
i have created a fiddle http://jsfiddle.net/h9D5W/
EDIT
here my variable string contains only user names i can't append id's with user names for example 1:first user, so the exact match will not be there in the string variable.
I have removed the starting digits, underscore and ending comma.
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
var re = new RegExp('\\d:*'+string+',*',"g");
var text = $('#textinput').val().replace(re, '');;
$('#textinput').val(text);
});
});
Check the demo
http://jsfiddle.net/yKfur/1/
In your JavaScript code, string is a variable. You'd need to initiate the RegExp class to generate the pattern:
Also, please refrain from using variable name like string. It's the name of a global object.
var s = 'first user';
var x = $( '#textinput' ).val().replace(new RegExp(s, 'g'), '');
// use the new variable x as you wish
You should use RegExp, You need to initialize it with string variable.
Use
$(".click").click(function () {
var string = 'first user';
var re = new RegExp(string,"g"); //initialize RegExp
var text = $('#textinput').val().replace(re, ''); //Get replaced text
$('#textinput').val(text); //Reset its value
});
DEMO
EDIT
here i cant use 1:first user in the variable
$(".click").click(function () {
var arr = $('#textinput').val().split(','); //Here used split method to split string ',' as deliminator
$('#textinput').val(arr[arr.length - 1]);
});
DEMO
You can use a regular expression like:
var text = '1:first user,2:second user,3:third user';
var s = 'first user';
var re = new RegExp('^\\d+:' + s + ',?|,\\d+:' + s + '\\b');
text.replace(re, '') // '2:second user,3:third user'
I'm sure there's a shorter one though.
I have updated your fiddle
first, i split your string into array
var inputArr = ($('#textinput').val()).split(',');
so i can check each set of words using for loop,
for (i = 0; i < inputArr.length; i++) {
if (inputArr[i].indexOf(string) == -1) {
newStr = newStr + inputArr[i] + ',';
}
}
then i set the new value using substring to eliminate the last comma appended.
$('#textinput').val(newStr.substring(0, newStr.length - 1));

Concatenating with Regular Expressions

I have a JQuery function that grabs the URL path and adds it as a body class as such:
var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, " ");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace(" ","");
var newClass = pathSlashesReplacedNoFirstDash.replace(/\(\d*\)/g, '').replace(/\s/, '-');
$("body").addClass(newClass);
if ( $("body").attr("class") == "")
{
$("body").addClass("class");
}
.. so if the url is something like /myapp/user/list, the body class ends up as:
<body class="myapp-user list">
The issue is I would like to have all three words with dashes so it should be:
<body class="myapp-user-list">
.. and then I can theme using the CSS:
.myapp-user-list {
}
I am pretty sure there is an issue with my RegEx but I cannot figure out where. I tried various text functions but then the problem was that it grabbed all the text from the page and put that in as the body class:
var text = $(this).text();
var newClass = $.trim(text.replace(/\(\d*\)/g, '').toLowerCase()).replace(/\s/, '-');
Try :
var newClass = location.pathname.split('/').join('-').replace(/(^-|-$)/g,''),
$body = $("body").addClass(newClass);
if ($body.attr("class") == "") {
$body.addClass("class");
}
I would avoid the class name class. It could give problems.
Try adding g modifier to the second replace to replace all white spaces and not just the first.
var newClass = pathSlashesReplacedNoFirstDash.replace(/\(\d*\)/g, '').replace(/\s/g, '-');
I think that applying these two regexps will do the job.
"/\//-/g" Will change all slashes to -
"/-//" Will only remove the first -

How to give a value of 1 to a textbox with a class

I want to know if the code below removes all input type='text' values back to "":
var inp = document.getElementsByTagName('input');
for (var i = inp.length - 1; i >= 0; i--) {
if ('text' === inp[i].type) inp[i].value = "";
}
Then I want to know if I have an input which is type='text' but which class is .num_questions. How can I code that so that it looks for the class name and gives it a value of "1"?
There is a property className on the Html Dom Element.
function hasCssClass(elt,clz) {
return elt.className.match(new RegExp('(\\s+|^)'+clz+'(\\s+|$)'));
}
var inp = document.getElementsByTagName('input');
for (var i = inp.length-1; i>=0; i--) {
if ('text'===inp[i].type && hasCssClass(inp[i],'num_questions')) {
inp[i].value = "?";
}
}
http://jsbin.com/aluzuv/2
EDIT - followup as requested.
Each HTML DOM Element has a className property, which is a string, containing a list of whitespace-separated CSS classes that apply to the element. In order to determine if a class applies to a particular element, you need to search for that string, in the list.
There are a couple ways to do it. One way is to split the className string by whitespace, and then see if your desired class (needle) is equal to any of the elements in the resulting string array. This might be something like this:
function hasCssClass(elt, clz) {
var classes = elt.className.split(/\s+/);
for(i=0; i<classes.Length;i++) {
if (clz == classes[i]) return true;
}
return false;
}
Another way is to use a regex match; that's what I did, because to me it's more succint. The regex I used looks for something, followed by the classname, followed by something else. The first something is (\\s+|^) , which in English means "one or more whitespace characters, OR, the beginning of the string." The something else is (\\s+|$), which in English is, "one or more whitespace characters, OR the end of the string." Therefore, the entire regex matches a string which consists of:
whitespace or beginning-of-string
desired classname
whitespace or end-of-string
Well, i don't think your question should be downvoted, handling classNames is not easy in javascript. So here is my answer:
var inp = document.getElementsByTagName('input');
for (var i = inp.length-1; i>=0; i--) {
if ('text'===inp[i].type) {
if(inp[i].className.indexOf('num_questions') > -1){
inp[i].value = "1";
} else{
inp[i].value = "";
}
}
}

Converting HTML to its safe entities with Javascript

I'm trying to convert characters like < and > into < and > etc.
User input is taken from a text box, and then copied into a DIV called changer.
here's my code:
function updateChanger() {
var message = document.getElementById('like').value;
message = convertHTML(message);
document.getElementById('changer').innerHTML = message;
}
function convertHTML(input)
{
input = input.replace('<', '<');
input = input.replace('>', '>');
return input;
}
But it doesn't seem to replace >, only <. Also tried like this:
input = input.replace('<', '<').replace('>', '>');
But I get the same result.
Can anyone point out what I'm doing wrong here? Cheers.
A more robust way to do this is to create an HTML text node; that way all of the other potentially invalid content (there's more than just < and >) is converted. For example:
var message = document.getElementById('like').value;
document.getElementById('changer').appendChild(document.createTextNode(message));
UPDATE
You mentioned that your event was firing upon each key press. If that's what's triggering this code, you'll want to remove what was previously in the div before appending the text. An easy way to do that is like this:
var message = document.getElementById('like').value;
var changer = document.getElementById('changer');
changer.innerHTML = '';
changer.appendChild(document.createTextNode(message));
Try something like this:
function convertHTML(input)
{
input = input.replace(/>/g, '>');
input = input.replace(/</g, '<');
return input;
}
replace only replaces the first occurrence of > or < in the string, in order to replace all occurrences of < or >, use regular expressions with the g param to ensure the entire string is searched for all occurrences of the values.

Categories

Resources