Javascript - remove a string in the middle of a string - javascript

Thank you everyone for your great help !
Sorry, I have to edit my question.
What if the "-6.7.8" is a random string that starts with "-" and has two "." between random numbers? such as "-609.7892.805667"?
===============
I am new to JavaScript, could someone help me for the following question?
I have a string AB.CD.1.23.3-609.7.8.EF.HI
I would like to break it into two strings: AB.CD.1.2.3.EF.HI (remove -609.7.8 in the middle) and AB.CD.6.7.8.EF.HI (remove 1.23.3- in the middle).
Is there an easy way to do it?
Thank you very much!

var s = "AB.CD.1.23.3-609.7.8.EF.HI";
var a = s.replace("-609.7.8","");
var b = s.replace("1.23.3-","");
console.log(a); //AB.CD.1.23.3.EF.HI
console.log(b); //AB.CD.609.7.8.EF.HI

You could use
str.replace();
var str = "AB.CD.1.2.3-6.7.8.EF.HI";
var str1 = str.replace("-6.7.8",""); // should return "AB.CD.1.2.3.EF.HI"
var str2 = str.replace("1.2.3-",""); // should return "AB.CD.6.7.8.EF.HI"

Use split() in String.prototype.split
var myString = "AB.CD.1.23.3-609.7.8.EF.HI";
var splits1 = myString.split("-609.7.8");
console.log(splits1);
var splits2 = myString.split("1.23.3-");
console.log(splits2);

With regular expressions:
s = 'AB.CD.1.23.3-609.7.8.EF.HI'
var re = /([A-Z]+\.[A-Z]+)\.([0-9]+\.[0-9]+.[0-9]+)-([0-9]+\.[0-9]+.[0-9]+)\.([A-Z]+\.[A-Z]+)/
matches = re.exec(s)
a = matches[1] + '.' + matches[2] + '.' + matches[4] // "AB.CD.1.23.3.EF.HI"
b = matches[1] + '.' + matches[3] + '.' + matches[4] // "AB.CD.609.7.8.EF.HI"

Related

Random character in RegEx replace

I want to replace G$0 in the string gantt(G$0,$A4,$B4) with gantt(<>G$0<>,$A4,$B4). So I have the following code:
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var val2 = val.replace(/\$/, "\\$")
var reg = new RegExp(val2, 'g');
var str = str.replace(reg, '<>' + val + '<>');
The result in IE is: =gantt(<>GG$0<>,$A4,$B4)  (note the GG). The problem seems to be IE10 specific.
Why is this happening, is this an IE bug?
The replace should assume a string could contain multiple instances of **G$0**.
There's no need to use RegEx at all. Stick to regular string replacement, and you won't have to escape the val string.
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var result = str.replace(val, '<>' + val + '<>');
If you want to replace multiple instances of val this can be done with .split and .join:
var str = '=gantt(G$0,$A4,$B4,G$0) ';
var val = "G$0";
var result = str.split(val).join('<>' + val + '<>');

Jquery - Add character after the first character of a string?

Say for example I have
var input = "C\\\\Program Files\\\\Need for Speed";
var output = do_it(input, ':');
Now, I would like output to have the value below :
C:\\\\Program Files\\\\Need for Speed
I need to add a character to the given string just after the first character. How can I achieve that using javascript or jquery ?
Thanks in advance
It's probably not the most efficient way, but I would do something like:
(note: this is just pseudocode)
var output = input[0] + ":" + input.substr(1, input.length);
you can use this like
String.prototype.addAt = function (index, character) {
return this.substr(0, index - 1) + character + this.substr(index-1 + character.length-1);
}
var input = "C\\Program Files\\Need for Speed";
var result = input.addAt(2, ':');
Heres one way of doing it:
Fiddle: http://jsfiddle.net/FjfB9/
var input = "C\\Program Files\\Need for Speed"
var do_it = function(str, char) {
var str = str.split(''),
temp = str.shift()
str.unshift(temp, char)
return str.join('')
}
console.log(do_it(input, ":"))

Replacing the last character in a string javascript

How do we replace last character of a string?
SetCookie('pre_checkbox', "111111111111 11 ")
checkbox_data1 = GetCookie('pre_checkbox');
if(checkbox_data1[checkbox_data1.length-1]==" "){
checkbox_data1[checkbox_data1.length-1]= '1';
console.log(checkbox_data1+"after");
}
out put on console : 111111111111 11 after
Last character was not replaced by '1' dont know why
also tried : checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-1), "1");
could some one pls help me out
Simple regex replace should do what you want:
checkbox_data1 = checkbox_data1.replace(/.$/,1);
Generic version:
mystr = mystr.replace(/.$/,"replacement");
Remember that just calling str.replace() doesn't apply the change to str unless you do str = str.replace() - that is, apply the replace() function's return value back to the variable str
use regex...
var checkbox_data1 = '111111111111 11 ';
checkbox_data1.replace(/ $/,'$1');
console.log(checkbox_data1);
This will replace the last space in the string.
You have some space in our string please try it
checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-4), "1 ");
then add the space in
console.log(checkbox_data1+" after");
This is also a way, without regexp :)
var string = '111111111111 11 ';
var tempstr = '';
if (string[string.length - 1] === ' ') {
for (i = 0; i < string.length - 1; i += 1) {
tempstr += string[i];
}
tempstr += '1';
}
You can try this,
var checkbox_data1=checkbox_data1.replace(checkbox_data1.slice(-1),"+");
This will replace the last character of Your string with "+".
As Rob said, strings are immutable. Ex:
var str = "abc";
str[0] = "d";
console.log(str); // "abc" not "dbc"
You could do:
var str = "111 ";
str = str.substr(0, str.length-1) + "1"; // this makes a _new_ string

Remove a character at a certain position in a string - javascript [duplicate]

This question already has answers here:
How can I remove a character from a string using JavaScript?
(22 answers)
Closed 5 years ago.
Is there an easy way to remove the character at a certain position in javascript?
e.g. if I have the string "Hello World", can I remove the character at position 3?
the result I would be looking for would the following:
"Helo World"
This question isn't a duplicate of How can I remove a character from a string using JavaScript?, because this one is about removing the character at a specific position, and that question is about removing all instances of a character.
It depends how easy you find the following, which uses simple String methods (in this case slice()).
var str = "Hello World";
str = str.slice(0, 3) + str.slice(4);
console.log(str)
You can try it this way:
var str = "Hello World";
var position = 6; // its 1 based
var newStr = str.substring(0, position - 1) + str.substring(position, str.length);
alert(newStr);
Here is a live example: http://jsbin.com/ogagaq
Turn the string into array, cut a character at specified index and turn back to string
let str = 'Hello World'.split('')
str.splice(3, 1)
str = str.join('')
// str = 'Helo World'.
If you omit the particular index character then use this method
function removeByIndex(str,index) {
return str.slice(0,index) + str.slice(index+1);
}
var str = "Hello world", index=3;
console.log(removeByIndex(str,index));
// Output: "Helo world"
var str = 'Hello World';
str = setCharAt(str, 3, '');
alert(str);
function setCharAt(str, index, chr)
{
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
you can use substring() method. ex,
var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);
Hi starbeamrainbowlabs ,
You can do this with the following:
var oldValue = "pic quality, hello" ;
var newValue = "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);
I tested this in my javascript console so you can also check this out
Thanks
var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);
alert(result);
Value of i should not be less then 1.

Replace last occurrence of character in string

Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
You don't need jQuery, just a regular expression.
This will remove the last underscore:
var str = 'a_b_c';
console.log( str.replace(/_([^_]*)$/, '$1') ) //a_bc
This will replace it with the contents of the variable replacement:
var str = 'a_b_c',
replacement = '!';
console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c
No need for jQuery nor regex assuming the character you want to replace exists in the string
Replace last char in a string
str = str.substring(0,str.length-2)+otherchar
Replace last underscore in a string
var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)
or use one of the regular expressions from the other answers
var str1 = "Replace the full stop with a questionmark."
var str2 = "Replace last _ with another char other than the underscore _ near the end"
// Replace last char in a string
console.log(
str1.substring(0,str1.length-2)+"?"
)
// alternative syntax
console.log(
str1.slice(0,-1)+"?"
)
// Replace last underscore in a string
var pos = str2.lastIndexOf('_'), otherchar = "|";
console.log(
str2.substring(0,pos) + otherchar + str2.substring(pos+1)
)
// alternative syntax
console.log(
str2.slice(0,pos) + otherchar + str2.slice(pos+1)
)
What about this?
function replaceLast(x, y, z){
var a = x.split("");
a[x.lastIndexOf(y)] = z;
return a.join("");
}
replaceLast("Hello world!", "l", "x"); // Hello worxd!
Another super clear way of doing this could be as follows:
let modifiedString = originalString
.split('').reverse().join('')
.replace('_', '')
.split('').reverse().join('')
Keep it simple
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
var someString = "(/n{})+++(/n{})---(/n{})$$$";
var toRemove = "(/n{})"; // should find & remove last occurrence
function removeLast(s, r){
s = s.split(r)
return s.slice(0,-1).join(r) + s.pop()
}
console.log(
removeLast(someString, toRemove)
)
Breakdown:
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
Reverse the string, replace the char, reverse the string.
Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?
// Define variables
let haystack = 'I do not want to replace this, but this'
let needle = 'this'
let replacement = 'hey it works :)'
// Reverse it
haystack = Array.from(haystack).reverse().join('')
needle = Array.from(needle).reverse().join('')
replacement = Array.from(replacement).reverse().join('')
// Make the replacement
haystack = haystack.replace(needle, replacement)
// Reverse it back
let results = Array.from(haystack).reverse().join('')
console.log(results)
// 'I do not want to replace this, but hey it works :)'
This is very similar to mplungjan's answer, but can be a bit easier (especially if you need to do other string manipulation right after and want to keep it as an array)
Anyway, I just thought I'd put it out there in case someone prefers it.
var str = 'a_b_c';
str = str.split(''); //['a','_','b','_','c']
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']
str = str.join(''); //'a_b-c'
The '_' can be swapped out with the char you want to replace
And the '-' can be replaced with the char or string you want to replace it with
You can use this code
var str="test_String_ABC";
var strReplacedWith=" and ";
var currentIndex = str.lastIndexOf("_");
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);
alert(str);
This is a recursive way that removes multiple occurrences of "endchar":
function TrimEnd(str, endchar) {
while (str.endsWith(endchar) && str !== "" && endchar !== "") {
str = str.slice(0, -1);
}
return str;
}
var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");
console.log(res)

Categories

Resources