concat string using javascript - javascript

var str = 'abc 123 hello xyz';
How to concat above string to abc123helloxyz? I tried to trim but it left spaces still between characters. I can't use split(' ') too as the space is not one some time.

You might use a regex successfully. \s checks for the occurences for any white spaced charachters. + accounts for more than once occurences of spaces. and `/g' to check for continue searching even after the first occurences is found.
var str = 'abc 123 hello xyz';
str = str.replace(/\s+/g, "");
console.log(str);

Use a regex.
var newstr = str.replace(/ +/g, '')
This will replace any number of spaces with an empty string.
You can also expand it to include other whitespace characters like so
var newstr = str.replace(/[ \n\t\r]+/g, '')

Replace the spaces in the string:
str = str.replace(" ", "");
Edit: as has been brought to my attention, this only replaces the first occurrence of the space character. Using regex as per the other answers is indeed the correct way to do it.

The cleanest way is to use the following regex:
\s means "one space", and \s+ means "one or more spaces".
/g flag means (replace all occurrences) and replace with the empty string.
var str = 'abc 123 hello xyz';
console.log("Before: " + str);
str = str.replace(/\s+/g, "");
console.log("After: " + str);

Related

Regex: search speciale character and remove all spaces + breakable charachter

I would like to search for a space OR more spaces before [:?!] and replace it with
here is my code so far working for many situations except:
hello[ SPACES ]?
it should be
hello ?
text.replace(/ ([:?!])/g, " \$1");
Using Capturing Group
For one or more spaces followed by either a :, ? or ! mark. Capture the second part and use it in the replace string.
const str = "Hey ! Are you busy ?";
str.replace(/ +([:?!])/g, " $1");
console.log(str);
const str = 'Hi my name is mahish dino'
const k=str.replace(/\s/g, '`replace this space with any string or integer')
console.log(k)
using str.replace(/\s/g, '') method you can replace the space with any string.

can i replace regExp with another regExp?

var str='The_Andy_Griffith_Show'; // string to perform replace on
var regExp1=/\s|[A-Z]/g;
var regExp2=/[^A-Z]/g; // regular expression
var str2 =str.replace(regExp2,regExp1);
// expected output: The_ Andy_ Griffith_ Show
I want to replace all the first capital letters of a string with a space and that same letter, and if that's not possible is there a workaround?
If you want to add a space before any captial letter, it is enough to use
var str='The_Andy_Griffith_Show';
str = str.replace(/[A-Z]/g, ' $&')
console.log(str); // => " The_ Andy_ Griffith_ Show"
Here, /[A-Z]/g matches all ASCII uppercase letters and $& is a backreference to the whole match value.
If you want to only add a space before the first capital letter in a word, you need to use capturing groups and backreferences to thier values in the replacement pattern:
var str='The_Andy_Griffith_Show'; // string to perform replace on
str = str.replace(/(^|[^A-Z])([A-Z])/g, '$1 $2')
console.log(str); // => " The_ Andy_ Griffith_ Show"
Remove ^| if you do not want to add space before a capital letter at the string start (i.e. use /([^A-Z])([A-Z])/g).
Just an alternative to the other answers.
To get that expected result you could just match the non-uppercases that are followed by an uppercase character, then replace them with the match $& and a space.
For example:
var str='The_Andy_Griffith_Show';
str = str.replace(/[^A-Z](?=[A-Z])/g, '$& ')
console.log(str);
Or simply match those uppercases followed by an uppercase character.
var str='The_Andy_Griffith_Show';
str = str.replace(/[_](?=[A-Z])/g, '$& ')
console.log(str);
To add space to all occurrences of capital letters:
var str = 'The_Andy_Griffith_Show',
str2 = str.replace(/[A-Z]/g, letter => ` ${letter}`);
console.log(str2);
Notice that if you want no to add space to the first letter occurrence, just use the regular expression /(?!^)[A-Z]/g.

Return word before or after a string with newline characters

In short: I want to return the word right before or after a newline character in a string. How would I accomplish that?
I want to return: 1,150 and Svendborg
This is my string:
var newline = /\n/;
var str = "Specialzed Road Expert 2017\nkr.1,150 - Svendborg\n\nSpecialzed"
This will essentially match a whole line with a leading and trailing newline character with groups to match just the first and last "words".
var str = "Specialzed Road Expert 2017\nkr.1,150 - Svendborg\n\nSpecialzed";
var matches = str.match(/\n([^\s]+).*?([^\s]+)\n/);
console.log(matches);
Your words would be in matches[1] and matches[2] with matches[0] being the whole line.

How do I delete all characters starting from a specific text on a string

The best way to explain this is by example. I'm using jQuery to do this.
Example I have a string
var str = "1.) Ben"
how can I dynamically omit the character 1.) including the space such that str === "Ben"
str can be dynamic such that order can increment from ones, tens, to hundreds.
E.G.
var str = "52.) Ken Bush"
or
var str = "182.) Hailey Quen"
Expected output
str === "Ken Bush"
or
str === "Hailey Quen"
Example
var str = "182.) Hailey Quen"
var test = str.split(') ');
test = test[1];
//output "Hailey Quen"
You can use regex replacement to get what you want.
var str = "182.) Hailey"
var newStr = str.replace(/^\d+\.\)\s*/, '')
// Hailey
var s = "1456.) Hard Spocker".replace(/^\d+\.\)\s*/, '')
// Hard Spocker
^ makes sure that the pattern is matched at the start of the string only
\d+ will match one or more digits.
\. will match the . with escaping
) is a symbol so we need to escape it using \ as \)
\s* will match one or more spaces.
You can learn about these symbols here.
Try using .substring() and .indexOf() as shown :-
var str = "182.) Hailey Quen"
alert(str.substring(str.indexOf(' ')))
DEMO
OR use .split() as shown :-
var str = "182.) Hailey Quen"
alert($.trim(str.split(')')[1]))
DEMO
You can do it regular expression,
var str = "52.) Ken".replace(/\d+\.\)\s/g,"");
console.log(str); //Ken
DEMO
If you have zero or more than zero spaces after the ) symbol then you can use *,
var str = "52.) Ken".replace(/\d+\.\)\s*/g,"");
console.log(str); //Ken
Dismantling regex used,
/ states regex left border
\d d states normal character d, if we want to make it match
numbers then we have to escape it with \
+ It states that one or more number should be there.
\. Again . is a metacharacter to match any valid character, so
escape it.
\) Parenthesis is also a metacharacter to close a group, escape
it.
\s* 12.) can be followed by zero or more spaces.
/ states regex right boundary.
g global flag, which used to do a search recursively.
You can do it like this
var testURL = "182.) Hailey Quen";
var output = testURL.substring(testURL.lastIndexOf(")") + 1).trim();
console.log(output);
*trim function will help to remove extra space if any.Hope it will help

Remove ALL white spaces from text

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}

Categories