How can I delete a part of a string by using only the index (no regex in case the character at index exists elsewhere)?
I use this, but it seems extremely convulted!!
var str = "stringIwant to delete from";
var stringCodeLastIndex = str.length - 1;
var index2delete = 1;
var stringStart, stringEnd, finalString;
if (index2delete == 0) {
stringStart = "";
} else {
stringStart = str.substr(0, index2delete);
}
if (index2delete < stringCodeLastIndex) {
stringEnd = str.substr(index2delete + 1);
} else {
stringEnd = "";
}
finalString = stringStart + stringEnd;
substring is smart enough to handle invalid indexes on its own:
str = "someXXXstring";
del = 4;
len = 3
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestringXXX";
del = 10;
len = 20
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestring";
del = 0;
len = 200
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
In your case, it's easier to use slice():
finalString = str.slice(0,index2delete)+str.slice(index2delete+1)
If you want to remove more characters, you can have 2 indexes:
finalString = str.slice(0,start_index)+str.slice(endindex+1)
http://www.w3schools.com/jsref/jsref_slice_string.asp
To remove one specific index from your string:
str.substr(0, indexToDelete) + str.substr(indexToDelete+1, str.length);
to remove a range of indexes from your string:
str.substr(0, startIndexToDelete) + str.substr(endIndexToDelete+1, str.length);
var str = "stringIwant to delete from";
var index2delete = 1;
arStr = str.split(""); // Making a JS Array of each characters
arStr.splice(index2delete,1); // Using array method to remove one entry at specified index
var finalString = arStr.join(''); // Convert Array to String
Result :
sringIwant to delete from
fiddle
then create a substring and use replace('your substring', '') it will replace the part of your string with a empty space
Related
I have a < p > with 123456789 value
I need to convert my < p > value into 123.456.789 number. What's the easiest way to do this in js?
Try it using regex. The match() function creates an array and join('.') will join the array elements to the required output.
str = "123456789";
str = str.match(/.{1,3}/g).join('.')
console.log(str)
Try Using this function.
Useful for any number and for any delimeter you pass through.
function formatNumber(n, d) // n = number, d = delimeter
{
// round to 2 decimals if cents present
n = (Math.round(n * 100) / 100).toString().split('.');
var
myNum = n[0].toString(),
fmat = new Array(),
len = myNum.length,
i = 1, deci = (d == '.') ? '' : '.';
for (i; i < len + 1; i++)
fmat[i] = myNum.charAt(i - 1);
fmat = fmat.reverse();
for (i = 1; i < len; i++)
{
if (i % 3 == 0) {
fmat[i] += d;
}
}
var val = fmat.reverse().join('') +
(n[1] == null ? deci + '':
(deci + n[1])
);
return val;
}
var res = formatNumber(123456789,'.');
console.log(res);
You can use .match() with RegExp /\d{3}(?=\d{6}|\d{3}|$)/g to match three digits followed by six digits, three digits or end of string, chain .join() to array returned by .match() with parameter "."
var str = "123456789";
var res = str.match(/\d{3}(?=\d{6}|\d{3}|$)/g).join(".");
console.log(res);
Regex combined with html will be enough to get it to work beautifully:
$(".telephone").html(function () {;
return $(this).html().match(/[0-9]{3}/g).join('.');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="telephone">123456789</p>
I has use some jquery code, pls try this! hope this can help you! :)
$('.number').text(function () {
var txt = $(this).text();
return txt.replace(/\B(?=(?:\d{3})+(?!\d))/g, '.');
});
$(document).ready(function(){
$('.number').text(function () {
var txt = $(this).text();
return txt.replace(/\B(?=(?:\d{3})+(?!\d))/g, '.');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="number">123456789</p>
const convert= (str)=>{
let newStr=""
let pointer=0;
while(pointer < str.length){
newStr += str.charAt(pointer)
if(str.charAt(pointer) % 3 === 0 && pointer !== str.length-1){
newStr += "."
}
pointer++
}
console.log(newStr)
}
convert("123456789");
I need to split the string like this 123,145,678.00 and the input i type in the textbox is 123145678 , also it not allow special character and alphabetic characters .
I try the following
var format = function(num){
var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
if(str.indexOf(".") > 0) {
parts = str.split(".");
str = parts[0];
}
str = str.split("").reverse();
for(var j = 0, len = str.length; j < len; j++) {
if(str[j] != ",") {
output.push(str[j]);
if(i%3 == 0 && j < (len - 1)) {
output.push(",");
}
i++;
}
}
formatted = output.reverse().join("");
//var value = formatted + ((parts) ? "." + parts[1].substr(0, 2) : "");
//console.log(dotvalue.toFixed(2))
return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};
Try with this..I hope this will help
var format = function(num){
var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
if(str.indexOf(".") > 0) {
parts = str.split(".");
str = parts[0];
}
str = str.split("").reverse();
for(var j = 0, len = str.length; j < len; j++) {
if(str[j] != ",") {
output.push(str[j]);
if(i%3 == 0 && j < (len - 1)) {
output.push(",");
}
i++;
}
}
formatted = output.reverse().join("");
//var value = formatted + ((parts) ? "." + parts[1].substr(0, 2) : "");
//console.log(dotvalue.toFixed(2))
return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : "")+".00");
};
You could add some zeroes at the end, separate the string in parts, concat the last parts with dot and join the rest with comma.
var string = '123145678',
splitted = (string + '00').match(/^(...)(...)(...)(..)/);
splitted.shift();
splitted[2] += '.' + splitted.pop();
console.log(splitted.join(','));
var number = "35$$##G%%%%^^##dhdfhhdf00";
// converts string to number, strips letters + special characters
var newNumber = Number(number.replace(/[^0-9]+/ig, ""));
// built-in javascript number formatting
var results = newNumber.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
// $3,500.00
Fiddle: https://jsfiddle.net/qL0qg8g1/
Options for toLocaleString here
I've been stuck on this last part of my assignment for the longest time. I'm trying to loop through the alphabet using modulus. delta is the number of letters you have to move forward or backwards to get the real letter. SO if given getchars("H",-2), the function is supposed to return F. A problem arises however if the chars.charAt(chars.getIndexOf(data.charAt(i))) ever equals a number less than 0. I want to be able to give my function ("A", -1) or any negative number and have it return "Z".
This is an assignment for class so if possible please keep it to just modulus. I've been working on this last part for like 2 hours now.
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
delta = Math.min(chars.length, delta);
i = 0;
newString = "";
while (i < data.length)
{
if(delta <= 0)
{
foundAt = (chars.indexOf(data.charAt(i)) + delta) ;window.alert(foundAt)
//newString = newString + chars.charAt(foundAt);
//i = i + 1;
}
else if((chars.indexOf(data.charAt(i)) < 0))
{
foundAt = data.charAt(i);
newString = newString + foundAt;
i = i + 1;
}
else
{
foundAt = ((chars.indexOf(data.charAt(0 + i)) + delta)) % chars.length;window.alert(foundAt);
newString = newString + chars.charAt(foundAt);window.alert(newString);
i = i + 1;
}
}
//return newString;
}
To be flexible, you can use i = chars.length - 1; and first after that do the found at.
You have to use you own modulus function :
function modulus(n,m) {
return ((n%m)+m)%m;
};
With your following code :
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
i = 0;
newString = "";
while (i < data.length)
{
newString += chars.charAt(modulus(chars.indexOf(data[i])+delta,26))
i++;
}
return newString;
}
I have a variable which contains this:
var a = "hotelRoomNumber";
Is there a way I can create a new variable from this that contains: "Hotel Room Number" ? I need to do a split on the uppercase character but I've not seen this done anywhere before.
Well, you could use a regex, but it's simpler just to build a new string:
var a = "hotelRoomNumber";
var b = '';
if (a.length > 0) {
b += a[0].toUpperCase();
for (var i = 1; i != a.length; ++i) {
b += a[i] === a[i].toUpperCase() ? ' ' + a[i] : a[i];
}
}
// Now b === "Hotel Room Number"
var str = "mySampleString";
str = str.replace(/([A-Z])/g, ' $1').replace(/^./, function(str){ return str.toUpperCase(); });
http://jsfiddle.net/PrashantJ/zX8RL/1/
I have made a function here:
http://jsfiddle.net/wZf6Z/2/
function camelToSpaceSeperated(string)
{
var char, i, spaceSeperated = '';
// iterate through each char
for (i = 0; i < string.length; i++) {
char = string.charAt(i); // current char
if (i > 0 && char === char.toUpperCase()) { // if is uppercase
spaceSeperated += ' ' + char;
} else {
spaceSeperated += char;
}
}
// Make the first char uppercase
spaceSeperated = spaceSeperated.charAt(0).toUpperCase() + spaceSeperated.substr(1);
return spaceSeperated;
}
The general idea is to iterate through each char in the string, check if the current char is already uppercased, if so then prepend a space to it.
I have a function that needs to append a sequence of numbers (starting with 1) at the end of each word in the string. Here is my function:
function insertNum(str) {
var word = new Array();
word = str.split(" ");
return src[0] + "1 " + src[1] + "2 " + src[2] + "3 " + src[3];
}
insertNum("word word word word."); // return "word1 word2 word3 word4."
insertNum("word word word."); // return "word1 word2 word3."
This should do it...
function insertNum(str) {
var index = 1;
return str.replace(/\w\b/g, function(match) {
return match + index++;
});
}
jsFiddle.
An easy way:
function insertNum(str) {
var word = new Array();
word = str.split(" ");
var tmp = "";
for (i = 1; i <= word.length; i ++) {
tmp += word[i-1] + i + " ";
}
return tmp;
}
int count = 1;
String s = "This is nice";
String a[] = s.split(" ");
for(String m : a){
System.out.print(m + count++ + " ");
}