Replace all spaces in a string with '+' [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
I have a string that contains multiple spaces. I want to replace these with a plus symbol. I thought I could use
var str = 'a b c';
var replaced = str.replace(' ', '+');
but it only replaces the first occurrence. How can I get it replace all occurrences?

You need the /g (global) option, like this:
var replaced = str.replace(/ /g, '+');
You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.

Here's an alternative that doesn't require regex:
var str = 'a b c';
var replaced = str.split(' ').join('+');

var str = 'a b c';
var replaced = str.replace(/\s/g, '+');

You can also do it like:
str = str.replace(/\s/g, "+");
Have a look at this fiddle.

Use global search in the string. g flag
str.replace(/\s+/g, '+');
source: replaceAll function

Use a regular expression with the g modifier:
var replaced = str.replace(/ /g, '+');
From Using Regular Expressions with JavaScript and ActionScript:
/g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.

You need to look for some replaceAll option
str = str.replace(/ /g, "+");
this is a regular expression way of doing a replaceAll.
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};

NON BREAKING SPACE ISSUE
In some browsers
(MSIE "as usually" ;-))
replacing space in string ignores the non-breaking space (the 160 char code).
One should always replace like this:
myString.replace(/[ \u00A0]/, myReplaceString)
Very nice detailed explanation:
http://www.adamkoch.com/2009/07/25/white-space-and-character-160/

Do this recursively:
public String replaceSpace(String s){
if (s.length() < 2) {
if(s.equals(" "))
return "+";
else
return s;
}
if (s.charAt(0) == ' ')
return "+" + replaceSpace(s.substring(1));
else
return s.substring(0, 1) + replaceSpace(s.substring(1));
}

Related

JavaScript replace string and comma if comma exists else only the string

I got a string like:
var string = "string1,string2,string3,string4";
I got to replace a given value from the string. So the string for example becomes like this:
var replaced = "string1,string3,string4"; // `string2,` is replaced from the string
Ive tried to do it like this:
var valueToReplace = "string2";
var replace = string.replace(',' + string2 + ',', '');
But then the output is:
string1string3,string4
Or if i have to replace string4 then the replace function doesn't replace anything, because the comma doens't exist.
How can i replace the value and the commas if the comma(s) exists?
If the comma doesn't exists, then only replace the string.
Modern browsers
var result = string.split(',').filter( s => s !== 'string2').join(',');
For older browsers
var result = string.split(',').filter( function(s){ return s !== 'string2'}).join(',');
First you split string into array such as ['string1', 'string2', 'string3', 'string4' ]
Then you filter out unwanted item with filter. So you are left with ['string1', 'string3', 'string4' ]
join(',') convertes your array into string using , separator.
Split the string by comma.
You get all Strings as an array and remove the item you want.
Join back them by comma.
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var parts = string.split(",");
parts.splice(parts.indexOf(valueToReplace), 1);
var result = parts.join(",");
console.log(result);
You only need to replace one of the two commas not both, so :
var replace = string.replace(string2 + ',', '');
Or :
var replace = string.replace(',' + string2, '');
You can check for the comma by :
if (string.indexOf(',' + string2)>-1) {
var replace = string.replace(',' + string2, '');
else if (string.indexOf(string2 + ',', '')>-1) {
var replace = string.replace(string2 + ',', '');
} else { var replace = string.replace(string2,''); }
You should replace only 1 comma and also pass the correct variable to replace method such as
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var replaced = string.replace(valueToReplace + ',', '');
alert(replaced);
You can replace the string and check after that for the comma
var replace = string.replace(string2, '');
if(replace[replace.length - 1] === ',')
{
replace = replace.slice(0, -1);
}
You can use string function replace();
eg:
var string = "string1,string2,string3,string4";
var valueToReplace = ",string2";
var replaced = string.replace(valueToReplace,'');
or if you wish to divide it in substring you can use substr() function;
var string = "string1,string2,string3,string4";
firstComma = string.indexOf(',')
var replaced = string.substr(0,string.indexOf(','));
secondComma = string.indexOf(',', firstComma + 1)
replaced += string.substr(secondComma , string.length);
you can adjust length as per your choice of comma by adding or subtracting 1.
str = "string1,string2,string3"
tmp = []
match = "string3"
str.split(',').forEach(e=>{
if(e != match)
tmp.push(e)
})
console.log(tmp.join(','))
okay i got you. here you go.
Your question is - How can i replace the value and the commas if the comma(s) exists?
So I'm assuming that string contains spaces also.
So question is - how can we detect the comma existence in string?
Simple, use below Javascript condition -
var string = "string1 string2, string3, string4";
var stringToReplace = "string2";
var result;
if (string.search(stringToReplace + "[\,]") === -1) {
result = string.replace(stringToReplace,'');
} else {
result = string.replace(stringToReplace + ',','');
}
document.getElementById("result").innerHTML = result;
<p id="result"></p>

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 all occurrences except last?

I want to remove all occurrences of substring = . in a string except the last one.
E.G:
1.2.3.4
should become:
123.4
You can use regex with positive look ahead,
"1.2.3.4".replace(/[.](?=.*[.])/g, "");
2-liner:
function removeAllButLast(string, token) {
/* Requires STRING not contain TOKEN */
var parts = string.split(token);
return parts.slice(0,-1).join('') + token + parts.slice(-1)
}
Alternative version without the requirement on the string argument:
function removeAllButLast(string, token) {
var parts = string.split(token);
if (parts[1]===undefined)
return string;
else
return parts.slice(0,-1).join('') + token + parts.slice(-1)
}
Demo:
> removeAllButLast('a.b.c.d', '.')
"abc.d"
The following one-liner is a regular expression that takes advantage of the fact that the * character is greedy, and that replace will leave the string alone if no match is found. It works by matching [longest string including dots][dot] and leaving [rest of string], and if a match is found it strips all '.'s from it:
'a.b.c.d'.replace(/(.*)\./, x => x.replace(/\./g,'')+'.')
(If your string contains newlines, you will have to use [.\n] rather than naked .s)
You can do something like this:
var str = '1.2.3.4';
var last = str.lastIndexOf('.');
var butLast = str.substring(0, last).replace(/\./g, '');
var res = butLast + str.substring(last);
Live example:
http://jsfiddle.net/qwjaW/
You could take a positive lookahead (for keeping the last dot, if any) and replace the first coming dots.
var string = '1.2.3.4';
console.log(string.replace(/\.(?=.*\.)/g, ''));
A replaceAllButLast function is more useful than a removeAllButLast function. When you want to remove just replace with an empty string:
function replaceAllButLast(str, pOld, pNew) {
var parts = str.split(pOld)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var test = 'hello there hello there hello there'
test = replaceAllButLast(test, ' there', '')
console.log(test) // hello hello hello there
Found a much better way of doing this. Here is replaceAllButLast and appendAllButLast as they should be done. The latter does a replace whilst preserving the original match. To remove, just replace with an empty string.
var str = "hello there hello there hello there"
function replaceAllButLast(str, regex, replace) {
var reg = new RegExp(regex, 'g')
return str.replace(reg, function(match, offset, str) {
var follow = str.slice(offset);
var isLast = follow.match(reg).length == 1;
return (isLast) ? match : replace
})
}
function appendAllButLast(str, regex, append) {
var reg = new RegExp(regex, 'g')
return str.replace(reg, function(match, offset, str) {
var follow = str.slice(offset);
var isLast = follow.match(reg).length == 1;
return (isLast) ? match : match + append
})
}
var replaced = replaceAllButLast(str, / there/, ' world')
console.log(replaced)
var appended = appendAllButLast(str, / there/, ' fred')
console.log(appended)
Thanks to #leaf for these masterpieces which he gave here.
You could reverse the string, remove all occurrences of substring except the first, and reverse it again to get what you want.
function formatString() {
var arr = ('1.2.3.4').split('.');
var arrLen = arr.length-1;
var outputString = '.' + arr[arrLen];
for (var i=arr.length-2; i >= 0; i--) {
outputString = arr[i]+outputString;
}
alert(outputString);
}
See it in action here: http://jsbin.com/izebay
var s='1.2.3.4';
s=s.split('.');
s.splice(s.length-1,0,'.');
s.join('');
123.4

How do I enhance slugify to handle Camel Case?

I'd like to write a JavaScript function to slugify a string, with one more requirement: handle Camel Case. For example, thisIsCamelCase would become this-is-camel-case.
How do I modify a function like this to do so?
EDIT
Added full, answered example.
You just need to add one line of code to what you posted
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; });
This brings the remaining code to be
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; }); // camel case handling
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;",
to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(from[i], to[i]);
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
}
Edit :: I also deleted the useless new RegExp logic too.
Edit :: Added 'g' to find all caps, not just the first one.
This will help you!
var strings = 'toDo';
var i=0;
var ch='';
while (i < strings.length){
character = strings.charAt(i);
if (character == character.toUpperCase()) {
//alert ('upper case true' + character);
character = "-" + character.toLowerCase();
}
i++;
ch += character;
}
//to-do
alert(ch);
Try using:
str=str.toLowerCase() before or after the slugification.

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