How to remove all the white spaces between two words? - javascript

I have an input field on which the user types the city name, but what if the user types the city like this:
"New York "
" New York "
I used the trim function but that did not work, any suggestion?
const city = "New York ";
console.log(city.trim());
How can I remove all the white spaces so I can save the city in the state as "New York"?

You can also use replace to replace all consecutive space characters with one space:
const str = "New York "
" New York "
const res = str.replace(/\s+/gm, " ").trim()
console.log(res)
Alternatively, you can split the string by a space, filter out the empty items, then join back by a space:
const str = "New York "
" New York "
const res = str.split(" ").filter(e=>e).join(" ")
console.log(res)

Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method
const city = " New York ";
console.log(city.replace(/\s+/g, ' ').trim());

Related

Problem I get unwanted things with .replaceall

This function is for getting the link for my subcategories. Now the problem is I console.log() the values and I have the text "hire/indoor--outdoor-activities" which I don't want to have "--" between "indoor" and "outdoor". But if I remove .replaceAll and .replace the text is "Indoor & Outdoor Activities". The problem are the two blank spaces between indoor and & and outdoor and &. Is there a regex or something so I can have only one "-"?
const subcategoryLink = (sector) => {
const sectorLink = `hire/${sector}`
const lowerCaseLink = sectorLink.toLowerCase().replace('&', '').replaceAll(' ', '-')
console.log(lowerCaseLink)
return lowerCaseLink
}
subcategoryLink("Indoor & Outdoor Activities");
You can go ahead and replace any sequence of spaces and '&'s with a single dash using regex
sectorLink.toLowerCase().replaceAll(/[ &]+/g, '-')
const subcategoryLink = (sector) => {
const sectorLink = `hire/${sector}`
const lowerCaseLink =sectorLink.toLowerCase().replace(/\&/g, '').replace(' ',' ').replace(/ /g,'-');
console.log(lowerCaseLink);
return lowerCaseLink;
}
subcategoryLink("Indoor & Outdoor Activities");

jQuery Replace Second Space of Sentence

I want to replace second space occurrence of the sentence with a br.
I have tried this but it is deleting the rest.
var title = "My Title Needs Brace".split(" ").slice(0, 2).join(" ");
That will do the trick:
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Let's break it and see how it works:
First, we take the string and split it. we'll use " " as our separator
"My Title Needs Brace".split(' ')
// ["My", "Title", "Needs", "Brace"]
Second, we'll use reduce to combine the array back into one string
["My", "Title", "Needs", "Brace"]
.reduce(function (str, part) { return str + ' ' + part }, '');
// "My Title Needs Brace"
Why reduce and not join?
The advantage of reduce over join is that it allows us to use a function, which will give us a fine-grained control over how we join back each part of the string
Now, all that left is to replace the 2nd space with <br/>,
for that, we'll use the 3rd argument of the reduce function, which stands for the index, and ask:
is this the 3rd part? use <br/>
otherwise, use " "
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Note that this is the index of the string "part", not the spaces between them so the index is 2, not 1.
More about:
split
reduce
join
Try the following:
var title = "My Title Needs Brace".split(" ");
title.forEach(function(item, i, title){
if(i==1)
title[i] += "<br/>";
else
title[i] += ' ';
})
console.log(title.join(''));
I want to replace second space occurrence of the sentence with a br.
The simple way to do that is to add "<br/>" to the second element.
Here is the Code.
$(document).ready(function(){
var title = "My Title Needs Brace".split(" ");
title[1] = title[1]+"<br/>";
var newstr = title.join(" ");
$("#textd").html(newstr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textd">
</div>
maybe that will help :
var title = "My Title Needs Brace".split(" ");
t1=title [0]; My
t2=title[1]; // Title
t3=title[2]; // Needs
t4=title[3]; // Brace
you can drew here anything :
var htmlString = '' + t1 +''+ t2 + '<br />' + t3 +''+ t4 + '';
$('Anywhere').append(htmlString);
You can do this without splitting the string:
var title = 'My Title Needs Brace'.replace(/( .*?) /, '$1<br>');
Here, String.replace takes a RegExp and a string as arguments. The regex matches everything from the first space up through the second space, keeping everything except the second space in a capturing group. The string replaces the entire match with the contents of the capturing group, followed by '<br>'. Since the capturing group doesn't include the second space, this effectively only replaces the second space.

How to replace found regex sub string with spaces with equal length in javascript?

In javascript if I have something like
string.replace(new RegExp(regex, "ig"), " ")
this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?
so if regex was \d+, and the string was
"123hello4567"
it changes to
" hello "
Thanks
The replacement argument (2nd) to .replace can be a function - this function is called in turn with every matching part as the first argument
knowing the length of the matching part, you can return the same number of spaces as the replacement value
In the code below I use . as a replacement value to easily illustrate the code
Note: this uses String#repeat, which is not available in IE11 (but then, neither are arrow functions) but you can always use a polyfill and a transpiler
let regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), m => '.'.repeat(m.length)));
Internet Exploder friendly version
var regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), function (m) {
return Array(m.length+1).join('.');
}));
thanks to #nnnnnn for the shorter IE friendly version
"123hello4567".replace(new RegExp(/[\d]/, "ig"), " ")
1 => " "
2 => " "
3 => " "
" hello "
"123hello4567".replace(new RegExp(/[\d]+/, "ig"), " ")
123 => " "
4567 => " "
" hello "
If you just want to replace every digit with a space, keep it simple:
var str = "123hello4567";
var res = str.replace(/\d/g,' ');
" hello "
This answers your example, but not exactly your question. What if the regex could match on different numbers of spaces depending on the string, or it isn't as simple as /d more than once? You could do something like this:
var str = "123hello456789goodbye12and456hello12345678again123";
var regex = /(\d+)/;
var match = regex.exec(str);
while (match != null) {
// Create string of spaces of same length
var replaceSpaces = match[0].replace(/./g,' ');
str = str.replace(regex, replaceSpaces);
match = regex.exec(str);
}
" hello goodbye and hello again "
Which will loop through executing the regex (instead of using /g for global).
Performance wise this could likely be sped up by creating a new string of spaces with the length the same length as match[0]. This would remove the regex replace within the loop. If performance isn't a high priority, this should work fine.

Extracting a List of Decimal numbers

I have a textarea that will have one or more pairings that look like this,
Lat = 38.7970308
Long = -100.8665928
How can I extract the numbers using Javascript (negative sign included if there)? I want all the numbers listed.
You can use this regex:
var s ='Lat = 38.7970308\n' +
'Long = -100.8665928';
var m = s.match(/[+-]?(?:\d+(?:\.\d+)?|\.\d+)/g);
//=> ["38.7970308", "-100.8665928"]
Try this regex:
[\+\-]?\d+.?\d+$
/([+-]?(?:[0-9]+\.)?[0-9]+)/g
http://regex101.com/r/mC0yO2/1
You can use this pattern to basically extract all the numbers:
/-?\d+(?:\.\d+)?/g
If, as in your string example, you want to extract these numbers by pairs, you need to use capturing groups:
/^Lat = (-?\d+(?:\.\d+)?)\s*?\r?\nLong = (-?\d+(?:\.\d+)?)\s*?$/mg
for each pairs founded, the latitude is in the capture group 1 and the longitude in the capture group 2.
Note that this second pattern take in account that literal strings "Lat = " and "Long = " are at the start of a line, always in this order, and only separated by a newline character. (with the m modifier, ^ means "start of the line, and $ means "end of the line"). Trailing spaces are allowed with \s*? for each line.
Example:
var yourString = "Lat = 38.7970308\nLong = -100.8665928";
var myRe = /^Lat = (-?\d+(?:\.\d+)?)\s*?\r?\nLong = (-?\d+(?:\.\d+)?)\s*?$/mg;
var m;
while ((m = myRe.exec(yourString)) !== null) {
console.log(m[1] + "\t" + m[2]+ "\n\n");
}

javascript regular expression matching cityname

I have the following array of data named cityList:
var cityList = [
"Anaa, French Polynesia (AAA)",
"Arrabury, Australia (AAB)",
"Al Arish, Egypt (AAC)",
"Ad-Dabbah, Sudan (AAD)",
"Annaba, Algeria (AAE)",
"Apalachicola, United States (AAF)",
"Arapoti, Brazil (AAG)",
"Aachen, Germany (AAH)",
"Arraias, Brazil (AAI)",
"Awaradam, Suriname (AAJ)",
"Aranuka, Kiribati (AAK)",
"Aalborg, Denmark (AAL)"
];
I want to first search the city name starting at the beginning of the string.
Next I want to search the code portion of the string: AAA, AAB, AAC, etc...
I want to apply a search pattern as a javascript regular expression, first to the city name, and second to the city code.
Here are my regular expressions:
// this regular expression used for search city name
var matcher = new RegExp("^" + re, "i");
// this regular expression used for search city code
var matcher = new RegExp("([(*)])" + re, "i");
How do I combine these two regular expressions into a single regex that works as described?
I suggest this:
var myregexp = /^([^,]+),[^(]*\(([^()]+)\)/;
var match = myregexp.exec(subject);
if (match != null) {
city = match[1];
code = match[2];
}
Explanation:
^ # Start of string
( # Match and capture (group number 1):
[^,]+ # One or more characters except comma (alternatively insert city name)
) # End of group 1
, # Match a comma
[^(]* # Match any number of characters except an opening parenthesis
\( # Match an opening parenthesis
( # Match and capture (group number 2):
[^()]+ # One or more characters except parentheses (alt. insert city code)
) # End of group 2
\) # Match a closing parenthesis
This assumes that no city name will ever contain a comma (otherwise this regex would only capture the part before the comma), so you'd need to check your data if that's ever possible. I can't think of an example, but that's not saying anything :)
$("#leavingCity").autocomplete({
source: function(req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("/^([^,]+),[^(]*\(([^()]+)\)/", "g");
var a = $.grep(cityList, function(item,index) { return matcher.test(item); });
responseFn(a);
} });
Try this, regualr expression by Tim Pietzcker
This is the most elegant way I can do it:
var cityList = ["Anaa, French Polynesia (AAA)","Arrabury, Australia (AAB)","Al Arish, Egypt (AAC)","Ad-Dabbah, Sudan (AAD)","Annaba, Algeria (AAE)","Apalachicola, United States (AAF)","Arapoti, Brazil (AAG)","Aachen, Germany (AAH)","Arraias, Brazil (AAI)","Awaradam, Suriname (AAJ)","Aranuka, Kiribati (AAK)","Aalborg, Denmark (AAL)"];
var regex = /([a-z].+?),.+?\(([A-Z]{3,3})\)/gi, match, newList = [];
while (match = regex.exec(cityList)) {
newList.push(match[1]+" - "+match[2]);
}
alert(newList[7]);
// prints Aachen - AAH
If you don't understand how to use parentheses in your regex, I suggest you check out the site I learned from: http://www.regular-expressions.info/
Here I suggest a completly different approach (ECMA-262 standard).
As using the regex requires a linear search anyway, if you can pre-process the data, you can set up an array of city objects:
function City(name, country, code){
this.cityName = name;
this.cityCountry = country;
this.cityCode = code;
}
var cities = [];
cities.push(new City('Anaa', 'French Polynesia', 'AAA'));
// ... push the other cities
And a search function:
function GetCity(cityToSearch, cities){
var res = null;
for(i=0;i<cities.length;i++){
if(cities[i].city = cityToSearch
res = cities[i];
}
return res;
}
At run time:
var codeFound = '';
var cityFound = GetCity('Arraias');
if(cityFound != null)
codeFound = cityFound.cityCode;
Remark
In both case, if you are going to fill the cities array with all city of the world, the city name is not a key! For instance there are half a dozen of 'Springfield' in USA. In that case a better approach is to use a two-fields key.
I think you want to accomplish this in a few simple steps:
Split each string in your array before and after the first parenthesis
Apply your first regex to the first part of the string. Store the result as a boolean variable, perhaps named matchOne
Apply your second regex to the second part of the string (don't forget to remove the closing parenthesis). Store the result as a boolean variable, perhaps named matchTwo.
Test if either of the two mathes succeeded: return ( matchOne || matchTwo );
Use indexOf
Its more efficient and explicit of expectation. regex is unnecessary.
const isMatchX = cityList.indexOf('AAB');
const isMatchY = cityList.indexOf('Awar');
Alternatively you could so something like this but its way overkill when you can use indexOf:
const search = (cityList, re) => {
const strRegPart1 = "¬[^¬]*" + re + "[^¬]*";
const strRegPart2 = "¬[^¬]*\\([^\\)]*" + re + "[^\\)]*\\)($|¬)";
const regSearch = RegExp("(" + strRegPart1 + "|" + strRegPart2 + ")", "gi");
const strCityListMarked = '¬' + cityList.join('¬');
const arrMatch = strCityListMarked.match(regSearch);
return arrMatch && arrMatch[1].substr(1);
}

Categories

Resources