简体   繁体   English

需要删除句子中部的特殊字符,但不删除字符串的开头和结尾

[英]need to remove special characters in the midle of sentence but not starting and ending of the string

I have a string 我有一个弦

string= "& & This is&test release & this is rest release &";
Output ="& & This istest release  this is rest release &"

Input: 输入:

string ="& & This is&test release & this is rest release &";

Output should be 输出应为

"& & This istest release  this is rest release &";

But am getting output is 但是获得输出是

"& & This istest release & this is rest release &";

My code: 我的代码:

 var str = "& & & This is&test release * this is rest release & &"; var str2=""; var str1=str.split(' '); for(var i=0;i<str1.length;i++) { if(/^[0-9a-zA-Z]/.test(str1[i])) { str1[i]=str1[i].replace(/[^a-zA-Z ]/g, "") } str2=str1.join(' '); } console.log(str2); 

I am not sure about the white spaces in string here (do you actually need them ,but here's an alternative you can try) 我不确定这里的字符串中的空格(您实际上是否需要它们,但这是您可以尝试的替代方法)

 let string = "& & This is&test release & this is rest release &"; let a = string.split("&").map(el => { if (el == "" || el == " ") { el = " &" } return el }) let result = a.join(""); // join acc to gap you want console.log(result) 

Try 尝试

 let s= "& & This is&test release & this is rest release &"; let o= s.replace(/^([& ]*)(.*?)([& ]*)$/, (m,a,b,c)=> a+b.replace(/&/g,'')+c); console.log(o); 

Here is something I came up with that will work with any special characters. 我想出了一些可以与任何特殊字符一起使用的东西。

var str = "& & This is&test _&&release & this_is rest release &";
var replacedString = str.replace(/(\w\s*)([^a-zA-Z0-9]+)(\s*\w)/g, "$1 $3"); 
console.log(replacedString);

Output: 输出:

& & This is test  release  this is rest release &

The replace pattern will match any number of special characters between any alphanumeric character. 替换模式将匹配任何字母数字字符之间的任意数量的特殊字符。

what about this? 那这个呢? it works perfectly. 它完美地工作。 I splitted the string to start, middle and end. 我将字符串拆分为开始,中间和结尾。 then replaced the special characters only in the middle, and then joined all the 3 parts back. 然后仅在中间替换特殊字符,然后将3个部分全部合并回去。

 string= "& & This is&test release & this is rest release &"; i=string.search(/[\\w\\s]/i)//first letter j=string.search(/[\\w\\s][^\\w\\s]*$/i)//last letter start=string.substr(0,i) middle= string.substr(i,j-i+1) end=string.substr(j+1) middle=middle.replace(/[^\\w\\s]/gi,"")//replace only in the middle output=start+middle+end console.log(output) 

Hoped I helped you. 希望我能帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM