Javascript if string contains a space replace the space with a dash - javascript

I'm trying to write some code that will check if a previously defined variable has a space, and if it does, replace the space with a dash. This will be nested in another function.
function foo(){
// If stateName has a space replaces the space with a dash
window.open('http://website.html/state-solar-policy/' + stateName);
}

Use this regex:
stateName.replace(/\s/g,"-");
It will replace all white spaces chars with a dash (-)
Note that the regex will cause no troubles if the string doesn't have a space in it.
It replaces every white-space if finds with a dash, if it doesn't find, it does nothing.

var string = "blah blah blah"
var new_string = string.replace(" ", "-");

var string="john doe is great";
var dashedstring=string.split(" ").join("-");

Related

How to replace all \n with space? [duplicate]

I have a var that contains a big list of words (millions) in this format:
var words = "
car
house
home
computer
go
went
";
I want to make a function that will replace the newline between each word with space.
So the results would something look like this:
car house home computer go went
You can use the .replace() function:
words = words.replace(/\n/g, " ");
Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.
Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.
let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");
console.log("After:");
console.log(words);
In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use
var new_words = words.replace(/[\r\n]+/g," ");
See regex demo
To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:
[ - start of a positive character class matching any single char defined inside it:
\r - (\x0D) - \n] - a carriage return (CR)
\n - (\x0A) - a line feed character (LF)
\x0B - a line tabulation (LT)
\x0C - form feed (FF)
\u0085 - next line (NEL)
\u2028 - line separator (LS)
\u2029 - paragraph separator (PS)
] - end of the character class
+ - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
/g - find and replace all occurrences in the provided string.
var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Some simple solution would look like
words.replace(/(\n)/g," ");
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')

Replace all whitespace characters

I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?
I tried:
str.replace(/ /gi, "X")
You want \s
Matches a single white space
character, including space, tab, form
feed, line feed.
Equivalent to
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
in Firefox and [ \f\n\r\t\v] in IE.
str = str.replace(/\s/g, "X");
We can also use this if we want to change all multiple joined blank spaces with a single character:
str.replace(/\s+/g,'X');
See it in action here: https://regex101.com/r/d9d53G/1
Explanation
/ \s+ / g
\s+ matches any whitespace character (equal to [\r\n\t\f\v ])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Global pattern flags
g modifier: global. All matches (don't return after first match)
\s is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.
str.replace(/\s/g, "X")
Have you tried the \s?
str.replace(/\s/g, "X");
If you use
str.replace(/\s/g, "");
it replaces all whitespaces. For example:
var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
Try this:
str.replace(/\s/g, "X")
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"
You could use the function trim
let str = ' Hello World ';
alert (str.trim());
All the front and back spaces around Hello World would be removed.
Actually it has been worked but
just try this.
take the value /\s/g into a string variable like
String a = /\s/g;
str = str.replaceAll(a,"X");
I've used the "slugify" method from underscore.string and it worked like a charm:
https://github.com/epeli/underscore.string#slugifystring--string
The cool thing is that you can really just import this method, don't need to import the entire library.

regexp problem, the dot selects all text

I use some jquery to highlight search results. For some reason if i enter a basis dot, all of the text get selected. I use regex and replace to wrap the results in a tag to give the found matches a color.
the code that i use
var pattern = new.RegExp('('+$.unique(text.split(" ")).join("|")+")","gi");
how can i prevent that the dot selects all text, so i want to leave the point out of the code(the dot has no power)
You may be able to get there by doing this:
var pattern = new.RegExp('('+$.unique(text.replace('.', '\\.').split(" ")).join("|")+")","gi");
The idea here is that you're attempting to escape the period, which acts as a wild card in regex.
This will replace all special RegExp characters (except for | since you're using that to join the terms) with their escaped version so you won't get unwanted matches or syntax errors:
var str = $.unique(text.split(" ")).join("|"),
pattern;
str = str.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=]/ig, "\\$&");
pattern = new RegExp('('+str+')', 'gi');
The dot is supposed to match all text (almost everything, really). If you want to match a period, you can just escape it as \..
If you have a period in your RegExp it's supposed to match any character besides newline characters. If you don't want that functionality you need to escape the period.
Example RegExp with period escaped /word\./
You need to escape the text you're putting into the regex, so that special characters don't have unwanted meanings. My code is based on some from phpjs.org:
var words = $.unique(text.split(" ")).join("|");
words = words.replace(/[.\\+*?\[\^\]$(){}=!<>|:\\-]/h, '\\$&'); // escape regex special chars
var pattern = new RegExp('(' + words + ")","gi");
This escapes the following characters: .\+*?[^]$(){}=!<>|:- with a backslash \ so you can safely insert them into your new RegExp construction.

Is there a JavaScript regular expression to remove all whitespace except newline?

How do I remove white spaces in a string but not new line character in JavaScript. I found a solution for C# , by using \t , but it's not supported in JavaScript.
To make it more clear, here's an example:
var s = "this\n is a\n te st"
using regexp method I expect it to return
"this\nisa\ntest"
[^\S\r\n]+
Not a non-whitespace char, not \r and not \n; one or more instances.
This will work, even on \t.
var newstr = s.replace(/ +?/g, '');
Although in Javascript / /g does match \t, I find it can hide the original intent as it reads as a match for the space character. The alternative would be to use a character collection explicitly listing the whitespace characters, excluding \n. i.e. /[ \t\r]+/g.
var newString = s.replace(/[ \t\r]+/g,"");
If you want to match every whitespace character that \s matches except for newlines, you could use this:
/[\t\v\f\r \u00a0\u2000-\u200b\u2028-\u2029\u3000]+/g
Note that this will remove carriage returns (\r), so if the input contains \r\n pairs, they will be converted to just \n. If you want to preserve carriage returns, just remove the \r from the regular expression.
Try this
var trimmedString = orgString.replace(/^\s+|\s+$/g, '') ;
This does the trick:
str.replace(/ /g, "")
and the space does NOT match tabs or linebreaks (CHROME45), no plus or questionmark is needed when replacing globally.
In Perl you have the "horizontal whitespace" shorthand \h to destinguish between linebreaks and spaces but unfortunately not in JavaScript.
The \t shorthand on the other hand IS supported in JavaScript, but it describes the tabulator only.
const str = "abc def ghi";
str.replace(/\s/g, "")
-> "abcdefghi"
try this '/^\\s*/'
code.replace(/^\s[^\S]*/gm, '')
works for me on text like:
#set($todayString = $util.time.nowEpochMilliSeconds())
#set($pk = $util.autoId())
$util.qr($ctx.stash.put("postId", $pk))
and removes the space/tabs before the first 3 lines with removing the spaces in the line.
*optimisation by #Toto:
code.replace(/^\s+/gm, '')

Match words separated by punctuation characters using regex

The sample string:
this!is.an?example
I want to match: this is an example.
I tried this:
<script type="text/javascript">
var string="this!is.an?example";
var pattern=/^\W/g;
alert(string.match(pattern));
</script>
Try this:
var words = "this!is.an?example".split(/[!.?,;:'"-]/);
This will create an string array containing each word.
If you want to turn it into a single string with the words separated by spaces, you can call words.join(" ").
EDIT: You could also split on \W (str.split(/\W/)), but that may match more characters than you want.
I can't understand why you want to explicitly match, but if your goal is to strip all punctuation, this would work:
var words = "this!is.an?example".split(/\W/);
words = words.join(' ');
\W will match any character except letters, digits and underscore.
If you want to split also on underscores, use this:
var words = "this!is.an?example_with|underscore".split(/\W|_/);
If you just want to match:
(\w|\.|!|\?)+
If you want to replace all punctuation with a whitespace, you could do this:
var str = str.replaceAll([^A-Za-z0-9]," ");
This replaces all non letters, numerals with a space.
/^\W/g means match a string where the first character is not a letter or number
and the string "this!is.an?example" obviously does not begin with a non-letter or non-number.
Remember that ^ means the whole string start with, not what you want to match start with. And also remember that capital \W is everything that is not matched by small \w. With that reminder what you probably want is:
var string="this!is.an?example";
var pattern=/(\w+)/g; // parens for capturing
alert(string.match(pattern).join(' ')); // if you don't join,
// some browsers will simply
// print "[object Object]"
// or something like it

Categories

Resources