String manipulation using javascript - 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));

Related

What will be the efficient way to Replace characters from within braces?

I have the below input
var input = (a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]
I need to remove the comma within the square brackets such that the final output will be
var output = (a-d){12-16},(M-Z){5-8},[#$%!^12+-23^!]
By solution
function test()
{
var input = '(a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]'; //input string
var splitByFirstBracket = input.split("["); //split the input by [ character
//merge the arrays where the second array is replaced by '' for ','
var output = splitByFirstBracket[0] + '[' + splitByFirstBracket[1].replace(/,/g,'');
alert(output);
}
It is providing the output correctly. Is there any better way - I am open both for JavaScript and JQuery.
Thanks in advance
You can use a regular expression replacement. The replacement can be a function, which receives the part of the input that was matched by the regexp, and then it can calculate the replacement. In this case, it would use another replace call to remove the commas.
var input = '(a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]'; //input string
var output = input.replace(/\[.*?\]/g, function(match) {
return match.replace(/,/g, '');
});
console.log(output);

Using simple angular filter to replace all occurences of certain strings in input string regardless of case and whitespaces

On my website I have a commentary field, where people can write whatever they want. To prevent spam and unserious comments, I'm using an angular filter in this way:
<span>{{comment | mouthWash}}</span>
The angular filter fetches an array containing banned words and scans through the input string and replaces all the occurences of the fetched words. The code for the filter is as below:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var regEx = new RegExp(word);
input = input.replace(regEx, "mooh");
});
return input;
};
});
bad-words.json is something like this:
["fuck", "ass", "shit", etc...]
So as an example <span>{{ "fuck this" | mouthWash}}</span> is outputted as <span>mooh this</span>
This is working perfectly, except that I want it to ignore whitespaces, to make it more bullet proof. I do not have much experience with regex, so if anyone had a simple soloution to this, I would be really grateful.
just change new RegExp(word, "ig"); to new RegExp("ig");
working example:
var words = ['pig', 'dog', '', ' ', 'cow'];
words.forEach(function(word) {
var regEx = new RegExp("ig");
word = word.replace(regEx, "mooh");
console.log(word);
});
Output:
"pmooh"
"dog"
""
" "
"cow"
This is the code I ended up with:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var str = word.substring(0,1)+"\\s*";
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
str = str + word.substring(word.length - 1,word.length);
var regEx = new RegExp(str, "gi");
input = input.replace(regEx, "mooh");
});
return input;
};
});
I created a for loop that would loop through every character of the banned word, adding the character together with \s* (so that spaces was ignored) to a string.
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
Then created a regExp from the string, by using the regExp constructor with the string as first parameter and "gi" as second, to make the regExp global and case insensitive.
var regEx = new RegExp(str, "gi");
Then that regex was used to search through input string and replace all matches with "mooh".

Replace with regExp in javascript

I have a problem with replace like this:
I have an array test :
test: Object
boolean: "true"
integer: "0"
values|+|0: "option_1"
values|+|1: "option_2"
and then i do parse like this:
for(var data in test){
for(var input in test[data]){
var input_aux = input.split('|+|');
if(input != ''){
$('table#'+table_id+' tbody td.'+input_aux[0]+' small').each(function(){
var text_highlighted = $(this).text().replace(new RegExp('(' + test[table][input] + ')', 'gi'), '<b>$1<\/b>');
$(this).html(text_highlighted);
}}}
what i'm trying to accomplish is to match the data from the array like option_1 that is in that table exactly option_1 and change the html of it to <b>option_1</b>.
And it's working fine my problem is like when i have the same key but different value like in the example above, it will highlight only option_2 and can't understand why, any idea?
The issue is the fact you are doing replacements even if there is no match. So you are reading the text() of all the elements and replacing it with that text. So you wipe out all of the existing html.
So check to see if there is a match before you do the replacement.
var re = new RegExp('(' + test[table][input] + ')', 'gi');
var txt = $(this).text();
if (txt.match(re)) {
var text_highlighted = txt.replace(re, '<b>$1<\/b>');
$(this).html(text_highlighted);
}
other option would be to use contains selector.

Remove string from string jQuery

Ignore my novice knowledge in jQuery. I started to learn recently and I have a challenge in front of me. I have a checkbox with names checkbox_0, checkbox_1 and want to remove "checkbox_" from the strings so that I would use the 0, 1 in my loop to extract the data for that index. Thanks
aData value alerts me the value checkbox_0, checkbox_1 etc. those are the checkboxes selected.
submitButton.on("click", function() {
$("Table :checked").each(function(e) {
var iData =Table.fnGetData( this.parentNode);
// Strip of the checkbox_ from the string
for(var i=0; i<=iData.length; i++) {
aData = iData[i][7];
}
alert(aData);
Table.fnDraw();
});
});
This is just a JavaScript, not a jQuery, thing.
To remove the first occurence of the work "checkbox_":
var updatedString = originalString.replace("checkbox_", "");
Or if you know it'll always be in the form "checkbox_n" where n is a digit,
var updatedString = originalString.substring(9);
...which chops the first nine characters off the string.
In either case, you end up with a string. If you want a number, you can use parseInt:
var updatedString = parseInt(originalString.replace("checkbox_", ""), 10);
// or
var updatedString = parseInt(originalString.substring(9), 10);
...or just put a + in front of it to cause an automatic cast (but note that in that case, both decimal and hex strings will be handled):
var updatedString = +originalString.replace("checkbox_", "");
// or
var updatedString = +originalString.substring(9);
Note that I've written updatedString = originalString.blah(...); but of course you can replace your reference, e.g., "originalString = originalString.blah(...);`.
More to explore:
MDN page on String
submitButton.on("click", function() {
$("Table :checked").each(function(e) {
var iData =Table.fnGetData( this.parentNode);
// Strip of the checkbox_ from the string
for(var i=0; i<=iData.length; i++) {
aData = iData[i].replace("checkbox_", "");
}
alert(aData);
Table.fnDraw();
});
});
To remove the checkbox_ part, you can simply do this:
cbName=cbName.replace("checkbox_", "");
To do this for all your checkboxes inside the .each() loop:
var cbIndex=this.name.replace("checkbox_", "");
//or...
var cbIndex=this.name.split("checkbox_").join("");
There are many ways to do it, some of them:
$("table :checked").each(function() {
var theNumber = this.name.replace(/\D/g, "");
var theNumber = this.name.replace(/[^\d]/g, ""); // or this
var theNumber = this.name.match(/\d/g).join(); // or this

Remove a letter(:) from a string

I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim() to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim() method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
You can replace all : characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim() function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace or substr methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
To chop the last character of a string use string.slice(0,-1)
You can use a regular expression to remove the colon (:).
Replace one instance:
var with_colon = 'Stuff:';
var regex = /([^:]*):/;
var without_colon = regex.exec(with_colon)[1];
alert(without_colon);
Result: Stuff
Replace all instances:
var with_colon = 'Stuff: Things:';
var without_colon = with_colon.replace(/([^:]*):/g,'$1');
alert(without_colon);
Result: Stuff Things
var myStr = "something:";
myStr = myStr.slice(0, -1);
var a="name:";
var b=a.split(":");
alert(b[0]);
one way is to use lastIndexOf
var str='Name:, Call:, Phone:';
var index=str.lastIndexOf(":");
alert(index);
var s=str.substring(0,index);
alert(s);
DEMO
This checks if the last character is a colon. If it is, the last character is removed.
if (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
If there can be multiple trailing colons, you can replace if with while, like this:
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
You could even make a generic trim function that accepts a string and a character and trims trailing instances of that character:
var trim = function(str, chr) {
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
return str;
}
function trim(str) {
str = str.replace(/^:*/,"");
return str.replace(/:*$/,"");
}
str = str.substring(0,str.lastIndexOf(":"));
Note that this removes everything from the last : to the end of the string (for example, any whitespace after the :).

Categories

Resources