Remove string from string jQuery - javascript

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

Related

Regular expression not capturing multiple characters [duplicate]

I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.
I tried:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
It still returns #box2 in the alert. How can I get it to work?
It needs to accommodate for any length number attached on the end.
For this specific example,
var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
In the general case:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Here's a bonus: regex generator.
function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​
Result
1234561613213213
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g, '');
Where txt is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well:
var num = txt.replace(/\D/g, '');
Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
Using the match function.
var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
I tried all the combinations cited in the previous answer with this code and got it working. It was the only one that worked on that string → (12) 3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
Result: "1234567890"
Obs: I know that a string like that will not be on the attribute, but whatever, the solution is better, because it’s more complete.
You may use the great parseInt() method.
It will convert the leading digits to a number:
parseInt("-10px");
// Will give you -10
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
Output: 25933473
Wrap it into a vanilla JavaScript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
Remember: if the number has a zero in front of it, the int won’t have it
If you want to parse a number from a price like $6,694.20, it can be done this way:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
Or via a function:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.
Number("strin[g]3".replace(/\D+/g, ""))
You can use a regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore.js' string library as follows:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
The result will be: 1
See: Underscore.string
Demo:
http://jsfiddle.net/abdennour/Vyqtt/
HTML code:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript code:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
If you have a suffix as follows:
href="box1az"
You can use the following demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Here's a solution that checks for no data:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234
With regular expressions, how to get numbers from a string, for example:
String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);
The result of myString is "24".
You can see an example of this running code at http://ideone.com/iOCf5G.
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
Please check the below JavaScript code. There you can get only a number.
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "") + '';
var s = str.split(',').join('');
alert(Number(s));
Output: 1234567789
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.
$('#help_number').keyup(function() {
$(this).val().match(/\d+/g).join("")
});
Explanation:
str = "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give an array of strings as output:
["34", "56766"]
 
str.match(/\d+/g).join("")
join() will convert and concatenate that array data into a single string.
Output:
"3456766"
In my example, I needed the output as 209-356-6788, so I used replace():
$('#help_number').keyup(function() {
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
Written without a regular expression:
// Without Regex
function extractNumber(string) {
let numArray = string.split('').map(item => {
if (typeof +item === 'number' && !isNaN(+item))
return +item
})
return +numArray.join('')
}
extractNumber('#1200milion$') // 1200
In one of my projects I had to take a rating value from a string. This is what I used:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call a function where you need it, with a parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');

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

Search through an entire string

How would you search through an entire string and display each item found in a div?
The thing I'm searching for is a license code which starts with NVOS and ends with ". I'd like to extract the entire code except for the "
The thing I want to parse would be like NVOS-ABCD-EFG-HIJK-LM52P" but I don't want the " included.
Here is what I'm trying:
var myRe = /^NVOS[^"]*/g;
var myArray = myRe.exec(document.getElementById("txt").value);
console.log(myArray)
for (i in myArray){
console.log(i)
}
Not working.
Use a regular expression.
var myString = document.body.innerHTML // substitute for your string
var regex = /NVOS[A-Z\-]+/g // /g (global) modifier searches for all matches
var matches = myString.match(regex);
for (var i=0; i<matches.length; i++)
console.log( matches[i] )
// NVOS-ABCD-EFG-HIJK-LM
// NVOS-ABCD-EFG-HIJK-LM
lests say that your string is str.
//check if the code even have this characters /x22 is for = " //
var newString = str.substr(str.indexOf("NVOS"),str.lastIndexOf("\x22") -1);
If you want to display each section in the console, then you could do it like this:
var licenseString = "NVOS-ABCD-EFG-HIJK-LM52P";
var stringSplit = licenseString.split("-");
for(var part in stringSplit) {
console.log(stringSplit[part]);
}

Remove character from string using javascript

i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';​​
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}

Regex replace string which is not float

I have a string, where I need to parse it as a float, but first I need to replace it, if it is not a number (an integer or a float), so I am trying to create an regular expression to do it
My tries results in NaN
One of my best tries is
var $replace = $text.replace(/^[^d.]*/, '');
var $float = parseFloat($replace);
Can anybody tell me, what I am doing wrong?
If you really want to replace everything thats not a digit, then try this:
var $replace = $text.replace(/[^\d.]/g, '');
var $float = parseFloat($replace);
This will replace a string of "123a3d2" with a string of "12332".
It looks like you want to strip "non-numeric" characters from the beginning of the string before converting it to float. A naive approach would be:
var s = input.replace(/^[^\d.]+/, '');
var n = parseFloat(s);
This works for inputs like "foo123" but will fail on "foo.bar.123". To parse this we need a more sophisticated regexp:
var s = input.replace(/^(.(?!\d)|\D)+/, '');
var n = parseFloat(s);
Another method is to strip the input char by char until we find a valid float:
function findValidFloat(str) {
for (var i = 0; i < str.length; i++) {
var f = parseFloat(str.substr(i))
if (!isNaN(f))
return f;
}
return NaN;
}
if (! isNaN($text))
$float = parseFloat($text);
else
$float = 0; // or whatever

Categories

Resources