How to remove underscore from beginning of string - javascript

I need to remove underscores from the beginning of a string(but only the beginning),
For example:
__Hello World
Should be converted to :
Hello World
But Hello_World should stay as Hello_World.
Tricky thing is I don't know how may underscores there could be 1,2 or 20.

You can pass a regex to replace(). /^_+/, says find any number of _ after at the beginning of the string:
let texts = ["__Hello World", "Hello_World", 'jello world_', '_Hello_World_', '___________Hello World']
let fixed = texts.map(t => t.replace(/^_+/, ''))
console.log(fixed)

Regex is pretty suited for this task:
let str = "__h_e_l_l_o__"
console.log(str.replace(/^_*/, ""));

Method 01:
var str = '__Hello World';
str = str.replace(/^_*/, "");
Method 02:
var str = '__Hello World';
while(str.startsWith('_')){
str = str.replace('_','');
}
console.log(str);
// Hello World

Related

Find and replace string text between two other string texts JS

I'm trying to find and replace a word in a string
Example:
let string =
`
Title: Hello World
Authors: Michael Dan
`
I need to find the Hellow World and replace with whatever I want, here is my attempt:
const replace = string.match(new RegExp("Title:" + "(.*)" + "Authors:")).replace("Test")
When you replace some text, it is not necessary to run String#match or RegExp#exec explicitly, String#replace does it under the hood.
You can use
let string = "\nTitle: Hello World\nAuthors: Michael Dan\n"
console.log(string.replace(/(Title:).*(?=\nAuthors:)/g, '$1 Test'));
The pattern matches
(Title:) - Group 1: Title: fixed string
.* - the rest of the line, any zero or more chars other than line break chars, CR and LF (we need to consume this text in order to remove it)
(?=\nAuthors:) - a positive lookahead that matches a location that is immediately followed with an LF char and Authors: string.
See the regex demo.
If there can be a CRLF line ending in your string, you will need to replace (?=\nAuthors:) with (?=\r?\nAuthors:) or (?=(?:\r\n?|\n)Authors:).
You might be better off converting to an object first and then just defining the title property:
let string =
`
Title: Hello World
Authors: Michael Dan
`
const stringLines = string.split('\n');
let stringAsObject = {};
stringLines.forEach(
(line) => {
if (line.includes(':')) {
stringAsObject[line.split(':')[0]] = line.split(':')[1];
}
}
);
stringAsObject.Title = 'NewValue';
You can use replace method like that:
string.replace("Hello World", "Test");
I can achieve this without regex. All you need is knowing the index of the string that you need to find.
var original = `
Title: Hello World
Authors: Michael Dan
`;
var stringToFind = "Hello World";
var indexOf = original.indexOf(stringToFind);
original = original.replace(original.substring(indexOf, indexOf + stringToFind.length), "Hey Universe!");
console.log(original)

How to get all the strings after a specific index?

Suppose I have this string: /ban 1d hello world which is essentially a command sended to a bot, meaning:
/ban specify to ban the user
1d represents the time
hello world is the reason
I need to get the reason, so I did:
let c = '/ban 1d hello world';
let arr = c.split(' ');
let result = c.replace(arr[0], '');
result = result.replace(arr[1], '')
alert(result);
this is working, but I would like to ask if there is a better way to achieve this.
Kind regards.
If you know that your reason will always be after the second space, you can do something like:
const c = '/ban 1d hello world';
const reason = c.split(' ').slice(2).join(' ');
A regular expression is a good way to match a known format.
You can match against a slash \/ followed by two words separated by spaces \S+ \S+ and then match the remaining characters (.*).
let c = '/ban 1d hello world';
let match = /\/\S+ \S+ (.*)/.exec(c);
let result = match[1];
console.log(result);
If you know the concrete format of the command parts, you could use a regex to get each individual part this way:
let c = '/ban 1d hello world';
var regex = /\/([a-z]+)\ ([0-9]+[a-z])\ (.*)/g;
var resultArray = regex.exec(c);
console.log(resultArray);
let command = resultArray[1] //ban
let time = resultArray[2]; //1d
let result = resultArray[3]; //hello world
console.log(result);

How I can replace a underscore with an space inside a word starting with an special char in javascript?

I have this string:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
And I'm trying to replace the ALL the underscores with spaces for any word starting with exclamation sing (!) so the string should looks like this one:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap Accessible},currentView:!map}";
I spent a few hours trying to figure out how to do that without success.
Try to use function replacement form (example):
str.replace(/!\w+/g, function(x) { return x.replace(/_/g, ' '); })
Regexp /!\w+/g selects all words started with "!". After that we replace each word x with result of x.replace(/_/g, ' ').
You can use the regex
!([^_]+)_([^]+)
and replace with $1 $2
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
console.log(str.replace(/!([^_]+)_([^]+)/g, "!$1 $2"));
(![^_]+)_([a-zA-Z0-9]+)
Try this.See demo.
http://regex101.com/r/tF5fT5/57
var re = /(![^_]+)_([a-zA-Z0-9]+)/gm;
var str = '{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}';
var subst = '$1 $2';
var result = str.replace(re, subst);

Replace last occurrence word in javascript [duplicate]

This question already has answers here:
JavaScript: replace last occurrence of text in a string
(16 answers)
Closed 8 years ago.
I have a problem with replacing last word in JS, I am still searching solution but i cannot get it.
I have this code:
var string = $(element).html(); // "abc def abc xyz"
var word = "abc";
var newWord = "test";
var newV = string.replace(new RegExp(word,'m'), newWord);
I want replace last word "abc" in this string, but now I can only replace all or first occurrence in string. How can I do this? Maybe is not good way?
Here is an idea ....
This is a case-sensitive string search version
var str = 'abc def abc xyz';
var word = 'abc';
var newWord = 'test';
// find the index of last time word was used
// please note lastIndexOf() is case sensitive
var n = str.lastIndexOf(word);
// slice the string in 2, one from the start to the lastIndexOf
// and then replace the word in the rest
str = str.slice(0, n) + str.slice(n).replace(word, newWord);
// result abc def test xyz
If you want a case-insensitive version, then the code has to be altered. Let me know and I can alter it for you. (PS. I am doing it so I will post it shortly)
Update: Here is a case-insensitive string search version
var str = 'abc def AbC xyz';
var word = 'abc';
var newWord = 'test';
// find the index of last time word was used
var n = str.toLowerCase().lastIndexOf(word.toLowerCase());
// slice the string in 2, one from the start to the lastIndexOf
// and then replace the word in the rest
var pat = new RegExp(word, 'i')
str = str.slice(0, n) + str.slice(n).replace(pat, newWord);
// result abc def test xyz
N.B. Above codes looks for a string. not whole word (ie with word boundaries in RegEx). If the string has to be a whole word, then it has to be reworked.
Update 2: Here is a case-insensitive whole word match version with RegEx
var str = 'abc def AbC abcde xyz';
var word = 'abc';
var newWord = 'test';
var pat = new RegExp('(\\b' + word + '\\b)(?!.*\\b\\1\\b)', 'i');
str = str.replace(pat, newWord);
// result abc def test abcde xyz
Good luck
:)
// create array
var words = $(element).html().split(" ");
// find last word and replace it
words[words.lastIndexOf("abc")] = newWord
// put it back together
words = words.join(" ");
You can use lookahead to get last word in a sentence:
var string = "abc def abc xyz";
var repl = string.replace(/\babc\b(?!.*?\babc\b)/, "test");
//=> "abc def test xyz"
You want to both:
match abc
check that there isn't another abc afterward in the string
So you can use:
abc(?!.*abc)
(?!...) is a negative lookahead, it will fail the whole regex match if what's inside the lookahead is matched.
Also be careful as this would match abc in abcdaire: if you only want abc as a separate word you need to add word boundaries \b:
\babc\b(?!.*\babc\b)
I'm not too familiar with JavaScript but you can probably twist this to fit your needs:
(\b\w+\b)(.*)(\1) replace with \1\2+'your_key_word'
See the demo to see what I mean.
try
var string = $(element).html(); // "abc def abc xyz"
var word = "abc";
var newWord = "test";
var newV = string.replace(new RegExp(word+'$'), newWord);
You can use the fact that the replace method replaces only the first occurrence of the target string if used without the global flag, and try something like:
"abc def abc xyz abc jkl".split(' ').reverse().join(' ').replace('abc', 'test').split(' ').reverse().join(' ')

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

I want to use str_replace or its similar alternative to replace some text in JavaScript.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);
should give
this is some sample text that i dont want to replace
If you are going to regex, what are the performance implications in
comparison to the built in replacement methods.
You would use the replace method:
text = text.replace('old', 'new');
The first argument is what you're looking for, obviously. It can also accept regular expressions.
Just remember that it does not change the original string. It only returns the new value.
More simply:
city_name=city_name.replace(/ /gi,'_');
Replaces all spaces with '_'!
All these methods don't modify original value, returns new strings.
var city_name = 'Some text with spaces';
Replaces 1st space with _
city_name.replace(' ', '_'); // Returns: "Some_text with spaces" (replaced only 1st match)
Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
city_name.replace(/ /gi,'_'); // Returns: Some_text_with_spaces
Replaces all spaces with _ without regex. Functional way.
city_name.split(' ').join('_'); // Returns: Some_text_with_spaces
You should write something like that :
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like #sorgit said). To replace all the "want" with "not want", us this code:
var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);
The variable "new_text" will result in being "this is some sample text that i dont want to replace".
To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!
that function replaces only one occurrence.. if you need to replace
multiple occurrences you should try this function:
http://phpjs.org/functions/str_replace:527
Not necessarily.
see the Hans Kesting answer:
city_name = city_name.replace(/ /gi,'_');
Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.
For a simple test run on the JS perf page, I've documented some of the results:
<script>
// Setup
var startString = "xxxxxxxxxabcxxxxxxabcxx";
var endStringRegEx = undefined;
var endStringString = undefined;
var endStringRegExNewStr = undefined;
var endStringRegExNew = undefined;
var endStringStoredRegEx = undefined;
var re = new RegExp("abc", "g");
</script>
<script>
// Tests
endStringRegEx = startString.replace(/abc/g, "def") // Regex
endStringString = startString.replace("abc", "def", "g") // String
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>
The results for Chrome 68 are as follows:
String replace: 9,936,093 operations/sec
Saved regex: 5,725,506 operations/sec
Regex: 5,529,504 operations/sec
New Regex String: 3,571,180 operations/sec
New Regex: 3,224,919 operations/sec
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }
var new_text = text.replace("want", "dont want");
hm.. Did you check replace() ?
Your code will look like this
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.
var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text) //ten, two, three, one, five, one
Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text) //ten, two, three, ten, five, ten
Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.
If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten
You can have more control over the replacement text using a function as the second argument.
In JavaScript, you call the replace method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want"), which will return the replaced string.
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
You can use
text.replace('old', 'new')
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.
Below is working example:
var text = "this is some sample text that i want to replace";
console.log(text.split("want").join("dont want"));
If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports.
For example tags:
//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')
or array's
//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )
function str_replace (search, replace, subject) {
var i = 0
var j = 0
var temp = ''
var repl = ''
var sl = 0
var fl = 0
var f = [].concat(search)
var r = [].concat(replace)
var s = subject
s = [].concat(s)
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + ''
repl = r[0]
s[i] = (temp).split(f[j]).join(repl)
if (typeof countObj !== 'undefined') {
countObj.value += ((temp.split(f[j])).length - 1)
}
}
}
return s[0]
}
var text = "this is some sample text that i want to replace";
var new_text = str_replace ("want", "dont want", text)
document.write(new_text)
for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js
You have the following options:
Replace the first occurrence
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)
Replace all occurrences - case sensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)
Replace all occurrences - case insensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/gi, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
console.log(new_text)
More info -> here
In Javascript, replace function available to replace sub-string from given string with new one.
Use:
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);
You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..
var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);
Here g modifier used to match globally all available matches.
Method to replace substring in a sentence using React:
const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
let newStr = "";
let i = 0;
sentence.split(" ").forEach(obj => {
if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
i = i + 1;
} else {
newStr = i === 0 ? obj : newStr + " " + obj;
i = i + 1;
}
});
return newStr;
};
RunMethodHere
If you don't want to use regex then you can use this function which will replace all in a string
Source Code:
function ReplaceAll(mystring, search_word, replace_with)
{
while (mystring.includes(search_word))
{
mystring = mystring.replace(search_word, replace_with);
}
return mystring;
}
How to use:
var mystring = ReplaceAll("Test Test", "Test", "Hello");
Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.
str.replace(regexp|substr, newSubStr|function);
Ex:
var str = 'this is some sample text that i want to replace';
var newstr = str.replace(/want/i, "dont't want");
document.write(newstr); // this is some sample text that i don't want to replace
ES2021 / ES12
String.prototype.replaceAll()
is trying to bring the full replacement option even when the input pattern is a string.
const str = "Backbencher sits at the Back";
const newStr = str.replaceAll("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Front"
1- String.prototype.replace()
We can do a full **replacement** only if we supply the pattern as a regular expression.
const str = "Backbencher sits at the Back";
const newStr = str.replace(/Back/g, "Front");
console.log(newStr); // "Frontbencher sits at the Front"
If the input pattern is a string, replace() method only replaces the first occurrence.
const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"
2- You can use split and join
const str = "Backbencher sits at the Back";
const newStr = str.split("Back").join("Front");
console.log(newStr); // "Frontbencher sits at the Front"
function str_replace($old, $new, $text)
{
return ($text+"").split($old).join($new);
}
You do not need additional libraries.
In ECMAScript 2021, you can use replaceAll can be used.
const str = "string1 string1 string1"
const newStr = str.replaceAll("string1", "string2");
console.log(newStr)
// "string2 string2 string2"
simplest form as below
if you need to replace only first occurrence
var newString = oldStr.replace('want', 'dont want');
if you want ot repalce all occurenace
var newString = oldStr.replace(want/g, 'dont want');
Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.
let replace_in_javascript= (replaceble, replaceTo, text) => {
return text.replace(replaceble, replaceTo)
}
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

Categories

Resources