Related
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.
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);
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
I need to split a keyword string and turn it into a comma delimited string. However, I need to get rid of extra spaces and any commas that the user has already input.
var keywordString = "ford tempo, with,,, sunroof";
Output to this string:
ford,tempo,with,sunroof,
I need the trailing comma and no spaces in the final output.
Not sure if I should go Regex or a string splitting function.
Anyone do something like this already?
I need to use javascript (or JQ).
EDIT (working solution):
var keywordString = ", ,, ford, tempo, with,,, sunroof,, ,";
//remove all commas; remove preceeding and trailing spaces; replace spaces with comma
str1 = keywordString.replace(/,/g , '').replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/[\s,]+/g, ',');
//add a comma at the end
str1 = str1 + ',';
console.log(str1);
You will need a regular expression in both cases. You could split and join the string:
str = str.split(/[\s,]+/).join();
This splits on and consumes any consecutive white spaces and commas. Similarly, you could just match and replace these characters:
str = str.replace(/[\s,]+/g, ',');
For the trailing comma, just append one
str = .... + ',';
If you have preceding and trailing white spaces, you should remove those first.
Reference: .split, .replace, Regular Expressions
In ES6:
var temp = str.split(",").map((item)=>item.trim());
In addition to Felix Kling's answer
If you have preceding and trailing white spaces, you should remove
those first.
It's possible to add an "extension method" to a JavaScript String by hooking into it's prototype. I've been using the following to trim preceding and trailing white-spaces, and thus far it's worked a treat:
// trims the leading and proceeding white-space
String.prototype.trim = function()
{
return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
I would keep it simple, and just match anything not allowed instead to join on:
str.split(/[^a-zA-Z-]+/g).filter(v=>v);
This matches all the gaps, no matter what non-allowed characters are in between. To get rid of the empty entry at the beginning and end, a simple filter for non-null values will do. See detailed explanation on regex101.
var str = ", ,, ford, tempo, with,,, sunroof,, ,";
var result = str.split(/[^a-zA-Z-]+/g).filter(v=>v).join(',');
console.info(result);
let query = "split me by space and remove trailing spaces and store in an array ";
let words = query.trim().split(" ");
console.log(words)
Output :
[
'split', 'me', 'by', 'space','and','remove', 'trailing', 'spaces', 'and', 'store', 'in', 'an', 'array'
]
If you just want to split, trim and join keeping the whitespaces, you can do this with lodash:
// The string to fix
var stringToFix = "The Wizard of Oz,Casablanca,The Green Mile";
// split, trim and join back without removing all the whitespaces between
var fixedString = _.map(stringToFix.split(','), _.trim).join(' == ');
// output: "The Wizard of Oz == Casablanca == The Green Mile"
console.log(fixedString);
<script src="https://cdn.jsdelivr.net/lodash/4.16.3/lodash.min.js"></script>
$("#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;
}