replace – with - using replace() - javascript

I have been using
var str = "Artist - Song";
str = str.replace("-", "feat");
to change some texts to "-".
Recently, I've noticed another "–" that the above code fails to replace.
This "–" seems a bit longer than the normal "-".
Is there any way to replace the longer one with the shorter "-"?
Any help is appreciated. Thanks
EDIT.
This is how the rest of the code is written.
var befComma = str.substr(0, str.indexOf('-'));
befComma.trim();
var afterhyp = str.substr(str.indexOf("-") + 1);
var changefeat = befComma.toUpperCase();

This "–" seems a bit longer than the normal "-".
Is there any way to replace the longer one with the shorter "-"?
Sure, you just do the same thing:
str = str.replace("–", "-");
Note that in both cases, you'll only replace the first match. If you want to replace all matches, see this question's answers, which point you at regular expressions with the g flag:
str = str.replace(/-/g, "feat");
str = str.replace(/–/g, "-");
I'm not quite sure why you'd want to replace the longer one with the shorter one, though; don't you want to replace both with feat?
If so, this replaces the first:
str = str.replace(/[-–]/, "feat");
And this replaces all:
str = str.replace(/[-–]/g, "feat");

Give this a shot:
var str = "Artist – Song";
str = str.replace("–", "-"); // Add in this function
str = str.replace("-", "feat");
This should replace the slightly longer "–" with the shorter more standard "-".

Related

Need to replace a character in a string with two new values

var Str = "_Hello_";
var newStr = Str.replaceAll("_", "<em>");
console.log(newStr);
it out puts <em>Hello<em>
I would like it to output <em>Hello</em>
but I have no idea how to get the </em> on the outer "_", if anyone could help I would really appreciate it. New to coding and finding this particularly difficult.
Replace two underscores in one go, using a regular expression for the first argument passed to replaceAll:
var Str = "_Hello_";
var newStr = Str.replaceAll(/_([^_]+)_/g, "<em>$1</em>");
console.log(newStr);
NB: it is more common practice to reserve PascalCase for class/constructor names, and use camelCase for other variables. So better str =, ...etc.
I would phrase this as a regex replacement using a capture group:
var str = "_Hello_ World!";
var newStr = str.replace(/_(.*?)_/g, "<em>$1</em>");
console.log(newStr);

Regular Expression to replace part of a string

I need to replace part of a string, it's dynamically generated so I'm never going to know what the string is.
Here's an example "session12_2" I need to replace the 2 at the end with a variable. The "session" text will always be the same but the number will change.
I've tried a standard replace but that didn't work (I didn't think it would).
Here's what I tried:
col1 = col1.replace('_'+oldnumber+'"', '_'+rowparts[2]+'"');
Edit: I'm looking for a reg ex that will replace '_'+oldnumber when it's found as part of a string.
If you will always have the "_" (underscore) as a divider you can do this:
str = str.split("_")[0]+"_"+rowparts[x];
This way you split the string using the underscore and then complete it with what you like, no regex needed.
var re = /session(\d+)_(\d+)/;
var str = 'session12_2';
var subst = 'session$1_'+rowparts[2];
var result = str.replace(re, subst);
Test: https://regex101.com/r/sH8gK8/1

JavaScript - strip everything before and including a character

I am relatively new to RegEx and am trying to achieve something which I think may be quite simple for someone more experienced than I.
I would like to construct a snippet in JavaScript which will take an input and strip anything before and including a specific character - in this case, an underscore.
Thus 0_test, 1_anotherTest, 2_someOtherTest would become test, anotherTest and someOtherTest, respectively.
Thanks in advance!
You can use the following regex (which can only be great if your special character is not known, see Alex's solution for just _):
^[^_]*_
Explanation:
^ - Beginning of a string
[^_]* - Any number of characters other than _
_ - Underscore
And replace with empty string.
var re = /^[^_]*_/;
var str = '1_anotherTest';
var subst = '';
document.getElementById("res").innerHTML = result = str.replace(re, subst);
<div id="res"/>
If you have to match before a digit, and you do not know which digit it can be, then the regex way is better (with the /^[^0-9]*[0-9]/ or /^\D*\d/ regex).
Simply read from its position to the end:
var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);

Remove all occurrences of text within string

Say I had a string in JavaScript that looked like this:
var str = "Item%5B9%5D.Something%5B0%5D.Prop1=1&Item%5B9%5D.Something%5B0%5D.Prop2=False&Item%5B9%5D.Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B1%5D.Prop1=2&Item%5B9%5D.Something%5B1%5D.Prop2=False&Item%5B9%5D.Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B2%5D.Prop1=3&Item%5B9%5D.Something%5B2%5D.Prop2=False&Item%5B9%5D.Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B3%5D.Prop1=4&Item%5B9%5D.Something%5B3%5D.Prop2=False&Item%5B9%5D.Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00"
and wanted it to look like this:
var str = "Something%5B0%5D.Prop1=1&Something%5B0%5D.Prop2=False&Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Something%5B1%5D.Prop1=2&Something%5B1%5D.Prop2=False&Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Something%5B2%5D.Prop1=3&Something%5B2%5D.Prop2=False&Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Something%5B3%5D.Prop1=4&Something%5B3%5D.Prop2=False&Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00"
i.e. remove all of the Item%5BX%5D. parts
How would I go about doing this? I thought of using something like:
str = str.substring(str.indexOf('Something'), str.length);
but obviously that only removes the first occurrence.
Also the number in-between the %5B and %5D could be anything, not necessarily 9.
This seems like something that should be simple but for some reason I'm stumped. I found a few similarish things on SO but nothing that handled all the above criteria.
You could use a regular expression :
str = str.replace(/Item[^.]+\./g, '');
or if you want something more precise because you'd want to keep Item%6B3%4D :
str = str.replace(/Item%5B.%5D\./g, '');
str = str.replace('Item%5B9%5D', '');
EDIT: Missed the part where 9 in the string could be any number. You can use:
str = str.replace(/Item%5B\d%5D\./g, '');
Avoid using a regular expression where complex "needle" escaping is required:
var str = "something complex full of http://, 'quotes' and more keep1 something complex full of http://, 'quotes' and more keep2 something complex full of http://, 'quotes' and more keep3"
var needle = "something complex full of http://, 'quotes' and more";
while( str.indexOf(needle) != '-1')
str = str.replace(needle,"");
document.write(str);
Outputs:
keep1 keep2 keep3
Here you go:
str = str.replace(/Item%5B\d%5D\./g,'');
Live Demo
Try using regular expressions:
str = str.replace(/Item%5B[^.]*%5D./g, '');
This assumes that you can have anything of any length between %5B and %5D.
JSFiddle
Using split() & join() method
var str = "Item%5B9%5D.Something%5B0%5D.Prop1=1&Item%5B9%5D.Something%5B0%5D.Prop2=False&Item%5B9%5D.Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B1%5D.Prop1=2&Item%5B9%5D.Something%5B1%5D.Prop2=False&Item%5B9%5D.Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B2%5D.Prop1=3&Item%5B9%5D.Something%5B2%5D.Prop2=False&Item%5B9%5D.Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B3%5D.Prop1=4&Item%5B9%5D.Something%5B3%5D.Prop2=False&Item%5B9%5D.Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00";
console.log(str.split(/Item%5B\d%5D\./g).join(''));

How to remove spaces from a string using JavaScript?

How to remove spaces in a string? For instance:
Input:
'/var/www/site/Brand new document.docx'
Output:
'/var/www/site/Brandnewdocument.docx'
This?
str = str.replace(/\s/g, '');
Example
var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s/g, '') );
Update: Based on this question, this:
str = str.replace(/\s+/g, '');
is a better solution. It produces the same result, but it does it faster.
The Regex
\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).
A great explanation for + can be found here.
As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.
var a = b = " /var/www/site/Brand new document.docx ";
console.log( a.split(' ').join('') );
console.log( b.replace( /\s/g, '') );
Two ways of doing this!
SHORTEST and FASTEST: str.replace(/ /g, '');
Benchmark:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
SHORT strings
Short string similar to examples from OP question
The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join solution. Change to \s or add + or i to regexp slows down processing.
LONG strings
For string about ~3 milion character results are:
regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
Following #rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case
So
var result = text.split(' ').join('')
operates faster than
var result = text.replace(/\s+/g, '')
On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.
On the other hand, \s+ handles wider variety of space characters. Among with \n and \t, it also matches \u00a0 character, and that is what is turned in, when getting text using textDomNode.nodeValue.
So I think that conclusion in here can be made as follows: if you only need to replace spaces ' ', use split/join. If there can be different symbols of symbol class - use replace(/\s+/g, '')
easy way
someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');
You also use one of the latest string methods of JS: replaceAll
'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
var input = '/var/www/site/Brand new document.docx';
//remove space
input = input.replace(/\s/g, '');
//make string lower
input = input.toLowerCase();
alert(input);
Click here for working example
Without regexp, it works fine for only one occurrence.
input = input.replace(' ', '');
This is faster as simple !
Could help some of you in some cases.
var output = '/var/www/site/Brand new document.docx'.replace(/ /g, "");
or
var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");
Note: Though you use 'g' or 'gi' for removing spaces both behaves the same.
If we use 'g' in the replace function, it will check for the exact match. but if we use 'gi', it ignores the case sensitivity.
for reference click here.
You can use regex to remove spaces from string`
let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');
Regex + Replace()
Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant. Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.
let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'
Split() + Join()
Using Split + Join allows for further chained manipulation of the string.
let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";
Using replaceAll seems like the simplest cleanest way. (I can't vouch for fastest)
'/var/www/site/Brand new document.docx'.replaceAll(' ', '')
See docs.
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
Easiest way to remove spaces from the string is use replace in this way
let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');
var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s\/g, '') );
----------
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
The output:
HelloWorld

Categories